本文共 10084 字,大约阅读时间需要 33 分钟。
aws中部署防火墙
by Harry Sauers
哈里·绍尔斯(Harry Sauers)
In this tutorial, you’ll learn how to use Amazon’s AWS SDK to deploy your Python application to a real-world server.
在本教程中,您将学习如何使用Amazon的AWS开发工具包将Python应用程序部署到实际服务器上。
Before we begin, you should have a working knowledge of Python, Git, and general cloud infrastructure. I recommend if you want to learn these fundamentals.
在开始之前,您应该具有Python,Git和常规云基础架构的工作知识。 如果您想学习这些基础知识,我建议您使用 。
Some of the Terminal/Bash commands I use are for an Ubuntu system. If they don’t work, check for your system’s equivalent.
我使用的一些Terminal / Bash命令用于Ubuntu系统。 如果它们不起作用,请检查系统是否等效。
Spin up your favorite and create a new project.
启动您最喜欢的并创建一个新项目。
Add print("Hello Python!")
to the file and run it to ensure your environment is set up correctly.
添加print("Hello Python!")
到文件并运行它,以确保正确设置环境。
Open a terminal and type sudo pip3 install boto3
and enter your sudo password, if needed.
打开终端,然后输入sudo pip3 install boto3
并输入您的sudo密码(如果需要)。
Add import boto3
to the top of your Python file.
将import boto3
添加到Python文件的顶部。
Before we can actually use anything on AWS, we need credentials for our AWS account. If you don’t have one, you can sign up here.
在我们可以在AWS上实际使用任何东西之前,我们需要我们的AWS账户凭证。 如果您没有,可以在这里注册。
Go to your and click “Add user” under the “Users” tab.
转到“ ,然后在“用户”选项卡下单击“添加用户”。
import csv
class Creds:
# credentials
username = “”
access_key_id = “”
secret_key = “”
def __init__(self, creds_file):
with open(creds_file) as file:
reader = csv.reader(file, delimiter=”,”)
header = next(reader)
creds_line = next(reader)
self.username = creds_line[0]
self.access_key_id = creds_line[2]
self.secret_key = creds_line[3]
Add from creds import Creds
to the top of your main Python file.
from creds import Creds
添加from creds import Creds
到主Python文件的顶部。
Initialize your Creds object in it: creds = Creds(“credentials.csv”)
在其中初始化您的Creds对象: creds = Creds(“credentials.csv”)
Great! Now we can use these to access Amazon Web Services.
大! 现在,我们可以使用它们来访问Amazon Web Services。
Add the following code after your creds
variable:
在您的creds
变量之后添加以下代码:
REGION = “us-east-2”
client = boto3.client(
‘ec2’,
aws_access_key_id=creds.access_key_id,
aws_secret_access_key=creds.secret_key,
region_name=REGION
)
Now, let’s provision a new instance of Ubuntu Server 18.04. This is eligible for Amazon’s free tier as well!
现在,让我们提供一个Ubuntu Server 18.04的新实例。 这也适用于亚马逊的免费套餐!
At the top of your file, add from botocore.exceptions import ClientError so your program knows how to handle errors.
在文件顶部, 从botocore.exceptions添加import ClientError,以便您的程序知道如何处理错误。
Head over to your AWS dashboard and go to EC2->Network & Security-> Key pairs and click “Create key pair.”
转到您的AWS仪表板,然后转到EC2->网络和安全->密钥对,然后单击“创建密钥对”。
Enter a name and hit “Create.” I used “robot” for mine. Though you should avoid hardcoding strings like this, we’ll overlook this, for now, to get it up and running.
输入名称,然后点击“创建”。 我使用“机器人”作为我的机器人。 尽管您应该避免像这样对字符串进行硬编码,但现在我们将忽略它以使其启动并运行。
To run commands on the server and open it to the Web, we have to create a security group and IAM role on AWS. Go to your dashboard.
要在服务器上运行命令并将其打开到Web,我们必须在AWS上创建安全组和IAM角色。 转到仪表板。
Copy down the group ID of the security group you just created, and paste it into a global variable called SECURITY_GROUP.
抄下刚刚创建的安全组的组ID,然后将其粘贴到名为SECURITY_GROUP的全局变量中。
Copy down the name of the IAM role and paste it into a global variable called IAM_PROFILE.
抄下 IAM角色的名称,并将其粘贴到名为IAM_PROFILE的全局变量中。
def provision_server():
# Ubuntu Server 18.04 ID from the AWS panel
image_id = "ami-0f65671a86f061fcd"
# Second smallest instance, free tier eligible.
instance_type = "t2.micro"
# Make this a command-line argument in the future.
keypair_name = "robot"
response = {}
try:
response = ec2.run_instances(ImageId=image_id,
InstanceType=instance_type,
KeyName=keypair_name,
SecurityGroupIds=[SECURITY_GROUP],
IamInstanceProfile={'Name': IAM_PROFILE},
MinCount=1,
MaxCount=1)
print(response['Instances'][0])
print("Provisioning instance…")
# wait for server to be provisioned before returning anything
time.sleep(60)
return str(response['Instances'][0]['InstanceId'])
except ClientError as e:
print(e)
Congratulations! You’re ready to provision your first EC2 server on Amazon. Learn how to configure its network and security settings and deploy a real web app to it in Part 2 when you’re ready to move on.
恭喜你! 您已经准备在Amazon上配置您的第一台EC2服务器。 当您准备好继续前进时,将在第2部分中了解如何配置其网络和安全设置以及如何向其部署真实的Web应用程序。
You made it! Let’s learn how to manage EC2 instances and deploy an application from Github to one.
你做到了! 让我们学习如何管理EC2实例以及如何从Github部署一个应用程序。
Amazon’Amazon’s SDK supports executing commands on the instance. This is very helpful. It allows us to manage the instance without having to worry about setting up a secure shell and the like.
Amazon的Amazon SDK支持在实例上执行命令。 这非常有帮助。 它使我们能够管理实例,而不必担心设置安全的shell等。
def get_instance_ids():
instance_id_list = []
instances = ec2.describe_instances()
instances = instances[‘Reservations’][0][‘Instances’]
for instance in instances:
instance_id_list.append(instance[‘InstanceId’])
return instance_id_list
def send_command_aws(commands=[“echo hello”], instance=”i-06cca6072e593a0ac”):
ssm_client = boto3.client(‘ssm’,
aws_access_key_id=creds.access_key_id,
aws_secret_access_key=creds.secret_key,
region_name=REGION)
response = ssm_client.send_command(
InstanceIds=[instance],
DocumentName=”AWS-RunShellScript”,
Parameters={‘commands’: commands}, )
command_id = response[‘Command’][‘CommandId’]
time.sleep(5)
output = ssm_client.get_command_invocation(
CommandId=command_id,
InstanceId=instance,
)
print(output)
def generate_git_commands(git_url=GIT_URL, start_command=”sudo python3 hellopython/app.py”, pip3_packages=[], additional_commands=[]):
commands = []
if “.git” in git_url:
git_url = git_url[:-4]
repo_name = git_url[git_url.rfind(‘/’):]
# install dependencies
commands.append(“sudo apt-get update”)
commands.append(“sudo apt-get install -y git”)
commands.append(“sudo apt-get install -y python3”)
commands.append(“sudo apt-get install -y python3-pip”)
commands.append(“sudo rm -R hellopython”)
commands.append(“pip3 — version”)
commands.append(“sudo git clone “ + git_url)
# commands.append(“cd “ + repo_name)
# install python dependencies
for dependency in pip3_packages:
commands.append(“sudo pip3 install “ + dependency)
# run any additional custom commands
for command in additional_commands:
commands.append(command)
# start program execution
commands.append(start_command)
return commands
GIT_URL = "https://github.com/hsauers5/hellopython"REGION = "us-east-2"SECURITY_GROUP = "sg-0c7a3bfa35c85f8ce"IAM_PROFILE = "Python-Tutorial"
send_command_aws(commands=generate_git_commands(GIT_URL, pip3_packages=["flask"]), instance=provision_server())
Run your code! python3 app.py
运行您的代码! python3 app.py
Congratulations! You just completed your first automated deployment using Amazon’s Boto3 SDK.
恭喜你! 您刚刚使用Amazon的Boto3 SDK完成了第一次自动部署。
You can view or download the complete repository here:
您可以在此处查看或下载完整的存储库: :
翻译自:
aws中部署防火墙
转载地址:http://cerwd.baihongyu.com/