aws中部署防火墙_如何在AWS中设置自动部署

aws中部署防火墙

by Harry Sauers

哈里·绍尔斯(Harry Sauers)

如何在AWS中设置自动部署 (How to set up automated deployment in AWS)

设置和配置服务器 (Provisioning and Configuring Servers)

介绍 (Introduction)

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 Codecademy if you want to learn these fundamentals.

在开始之前,您应该具有Python,Git和常规云基础架构的工作知识。 如果您想学习这些基础知识,我建议您使用Codecademy

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系统。 如果它们不起作用,请检查系统是否等效。

入门 (Getting Started)

  • Spin up your favorite Python IDE and create a new project.

    启动您最喜欢的Python IDE并创建一个新项目。

  • Create your main project file and name it whatever you want — I chose “app.py” for simplicity.

    创建您的主项目文件并随便命名—我为简单起见选择了“ app.py”。
  • Add print("Hello Python!") to the file and run it to ensure your environment is set up correctly.

    添加print("Hello Python!") 到文件并运行它,以确保正确设置环境。

  • Next, we need to install Amazon’s SDK. Though AWS does provide a standard HTTP API, the software development kit is much more robust. The SDK handles tedious and lower-level operations for you.r

    接下来,我们需要安装Amazon的SDK。 尽管AWS确实提供了标准的HTTP API,但是该软件开发套件更加强大。 SDK为您处理乏味的底层操作。
  • 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文件的顶部。

  • This allows us to use Amazon’s SDK in our Python application.

    这使我们能够在Python应用程序中使用Amazon的SDK。

AWS凭证 (AWS Credentials)

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 Identity and Access Management panel and click “Add user” under the “Users” tab.

    转到“ 身份和访问管理”面板 ,然后在“用户”选项卡下单击“添加用户”。

  • Enter a username and tick the box beside “programmatic access.”

    输入用户名,然后选中“程序访问”旁边的框。
  • Click “Next: Permissions” and create a new group, if needed.

    如果需要,请单击“下一步:权限”并创建一个新组。
  • For the purposes of this tutorial, I’ll create a new group with the “AdministratorAccess” policy. This gives us permission to manage everything in our AWS console programmatically.

    就本教程而言,我将使用“ AdministratorAccess”策略创建一个新组。 这使我们可以通过编程方式管理AWS控制台中的所有内容。
  • Click “Next: Tags” and add any relevant information. This is optional.

    单击“下一步:标签”,然后添加所有相关信息。 这是可选的。
  • Click “Review,” then “Create User.”

    点击“查看”,然后点击“创建用户”。
  • Download your security credentials (the CSV file) and copy it into your project’s root directory. If you’re using source control, be careful.

    下载您的安全凭证(CSV文件),并将其复制到项目的根目录中。 如果您使用的是源代码管理,请当心。

阅读证书 (Reading the Credentials)

  • Create a new file “creds.py” with the following code:

    使用以下代码创建一个新文件“ creds.py”:
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。

调配EC2服务器 (Provisioning an EC2 Server)

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角色。 转到仪表板。

创建一个安全组: (Creating a security group:)

  • Navigate to Network & Security -> Security Groups.

    导航到网络和安全->安全组。
  • Create a security group, and open ports 22, 80, 443, and 5000. This will allow general access to it from the Web. Allow all IPs to access them.

    创建一个安全组,并打开端口22、80、443和5000。这将允许从Web对其进行常规访问。 允许所有IP访问它们。
  • 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的全局变量中

创建IAM角色: (Creating an IAM role:)

  • Go to your AWS dashboard and navigate to the IAM service.

    转到您的AWS仪表板并导航到IAM服务。
  • Click on the “Roles” tab.

    点击“角色”标签。
  • Click “Create role” and select “EC2.” For the purposes of this tutorial, you’ll want to select “Administrator Access,” but in a real-world setting, this may not be appropriate.

    点击“创建角色”,然后选择“ EC2”。 就本教程而言,您将要选择“ Administrator Access”,但在实际设置中,这可能不合适。
  • Click through the rest of the steps to create a role.

    单击其余步骤以创建角色。
  • Copy down the name of the IAM role and paste it into a global variable called IAM_PROFILE.

    抄下 IAM角色的名称,并将其粘贴到名为IAM_PROFILE的全局变量中

  • Add this code to provision a minimal Ubuntu server from Amazon:

    添加以下代码以从亚马逊配置最小的Ubuntu服务器:
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应用程序。

部署您的应用 (Deploying Your Application)

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等。

  • First, we need to get a list of the instances in your private cloud:

    首先,我们需要获取私有云中实例的列表:
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
  • Add this code to be able to execute commands on your server’s terminal:

    添加以下代码以能够在服务器的终端上执行命令:
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)
  • Finally, we need to generate commands to install dependencies and deploy a Flask webapp from Github on the live server:

    最后,我们需要生成命令来安装依赖项并在实时服务器上从Github部署Flask Web应用程序:
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
  • Add these constants to the top of your program:

    将这些常量添加到程序的顶部:
GIT_URL = "https://github.com/hsauers5/hellopython"REGION = "us-east-2"SECURITY_GROUP = "sg-0c7a3bfa35c85f8ce"IAM_PROFILE = "Python-Tutorial"
  • Now, add this line to the bottom of your program:

    现在,将此行添加到程序的底部:
send_command_aws(commands=generate_git_commands(GIT_URL, pip3_packages=["flask"]), instance=provision_server())
  • Run your code! python3 app.py

    运行您的代码! python3 app.py

  • Head over to your EC2 panel, and copy the machine’s public DNS. Add “:5000” to it and navigate to it in your browser.

    转到您的EC2面板,然后复制计算机的公共DNS。 在其中添加“:5000”,然后在浏览器中导航到它。

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: https://github.com/hsauers5/AWS-Deployment

您可以在此处查看或下载完整的存储库: https : //github.com/hsauers5/AWS-Deployment

翻译自: https://www.freecodecamp.org/news/automated-deployment-in-aws-5aadc2e708a9/

aws中部署防火墙

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值