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中部署防火墻