使用Python自動化配置AWS EC2實例
背景介紹
AWS EC2是一種基礎(chǔ)架構(gòu)即服務(wù)(IaaS),用于提供可擴(kuò)展的計算資源,包括虛擬機(jī),存儲和網(wǎng)絡(luò)資源。 EC2實例是運行在虛擬機(jī)中的計算資源,它們可以通過AWS控制臺,CLI或API進(jìn)行創(chuàng)建,管理和終止。對于管理和維護(hù)大量的EC2實例,自動化是很重要的。
本文將介紹如何使用Python自動化配置AWS EC2實例,具體包括以下內(nèi)容:
1. 配置AWS憑證
2. 創(chuàng)建EC2實例
3. 配置EC2實例
4. 終止EC2實例
5. 實例化Python腳本
1. 配置AWS憑證
在使用Python與AWS進(jìn)行交互之前,需要配置AWS憑證。AWS支持多種憑證類型,如密鑰對,STS令牌等。在這里,我們將使用訪問密鑰對進(jìn)行身份驗證。密鑰對包括訪問密鑰ID和秘密訪問密鑰。以下是如何配置它們的步驟:
1. 登錄AWS控制臺并轉(zhuǎn)到IAM控制臺。
2. 選擇“訪問密鑰(訪問密鑰ID和秘密訪問密鑰)”選項卡。
3. 點擊“創(chuàng)建新的訪問密鑰”。
4. 下載新的訪問密鑰并存儲在本地機(jī)器上。
現(xiàn)在,您已經(jīng)擁有了AWS憑證。接下來,我們將使用Python和Boto3庫與AWS進(jìn)行交互。
2. 創(chuàng)建EC2實例
Boto3是一個Python庫,可用于與AWS進(jìn)行交互。使用以下代碼可以創(chuàng)建EC2實例:
import boto3ACCESS_KEY = 'YOUR_ACCESS_KEY'SECRET_KEY = 'YOUR_SECRET_KEY'REGION_NAME = 'us-west-2'ec2 = boto3.resource('ec2', aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY, region_name=REGION_NAME)ec2.create_instances(ImageId='ami-0c55b159cbfafe1f0', MinCount=1, MaxCount=1, InstanceType='t2.micro', KeyName='my-key-pair')
在這個例子中,我們指定了以下參數(shù):
- ImageId: EC2實例將使用的AMI ID。
- MinCount: 要創(chuàng)建的實例的最小數(shù)量。
- MaxCount: 要創(chuàng)建的實例的最大數(shù)量。
- InstanceType: 實例類型,例如t2.micro,m5.large等。
- KeyName: 使用的密鑰對名稱。
隨著實例的創(chuàng)建,您將獲得實例ID和IP地址。您可以使用這些信息來訪問EC2實例。
3. 配置EC2實例
一旦EC2實例創(chuàng)建成功,您需要配置它們以實現(xiàn)應(yīng)用程序或服務(wù)的要求。在這里,我們將使用Boto3庫來配置EC2實例。
a. 安裝所需的軟件包
在這個例子中,我們將使用Boto3庫來安裝所需的軟件包。
import boto3from botocore.exceptions import ClientErrorimport paramikoACCESS_KEY = 'YOUR_ACCESS_KEY'SECRET_KEY = 'YOUR_SECRET_KEY'REGION_NAME = 'us-west-2'ec2 = boto3.resource('ec2', aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY, region_name=REGION_NAME)instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])instance_ids = []for instance in instances: instance_ids.append(instance.id) for status in instance.state.values(): if status != 'running': print('Instance is not running') breakfor instance_id in instance_ids: instance = ec2.Instance(instance_id) ssh_client = paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_key = paramiko.RSAKey.generate(2048) ssh_key_file = 'my_key.pem' ssh_key.write_private_key_file(ssh_key_file) try: ssh_client.connect(hostname=instance.public_dns_name, username='ec2-user', pkey=ssh_key) stdin, stdout, stderr = ssh_client.exec_command('sudo yum update -y') print(stdout.read()) stdin, stdout, stderr = ssh_client.exec_command('sudo yum install -y httpd') print(stdout.read()) except ClientError as e: print(e) finally: ssh_client.close()
在這個例子中,我們使用Boto3庫來列出運行中的EC2實例,然后使用Paramiko庫來遠(yuǎn)程連接到EC2實例以安裝所需的軟件包。
b. 安全組規(guī)則
安全組規(guī)則是EC2實例的網(wǎng)絡(luò)防火墻配置。您可以使用Boto3庫添加或刪除安全組規(guī)則。以下是一個使用Boto3庫添加安全組規(guī)則的示例:
import boto3ACCESS_KEY = 'YOUR_ACCESS_KEY'SECRET_KEY = 'YOUR_SECRET_KEY'REGION_NAME = 'us-west-2'ec2 = boto3.client('ec2', aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY, region_name=REGION_NAME)response = ec2.authorize_security_group_ingress(GroupId='YOUR_SECURITY_GROUP_ID', IpPermissions=[ {'IpProtocol': 'tcp', 'FromPort': 80, 'ToPort': 80, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]} ])
在這個例子中,我們使用Boto3庫調(diào)用authorize_security_group_ingress函數(shù)添加TCP端口80的入站規(guī)則。
4. 終止EC2實例
終止EC2實例可以避免與AWS的不必要的費用。使用以下代碼可以終止EC2實例:
import boto3ACCESS_KEY = 'YOUR_ACCESS_KEY'SECRET_KEY = 'YOUR_SECRET_KEY'REGION_NAME = 'us-west-2'ec2 = boto3.resource('ec2', aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY, region_name=REGION_NAME)instance_ids = []instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])for instance in instances: instance_ids.append(instance.id) for status in instance.state.values(): if status != 'running': print('Instance is not running') breakif not instance_ids: print('No running instances.')else: ec2.instances.filter(InstanceIds=instance_ids).terminate()
在這個例子中,我們使用Boto3庫篩選正在運行的EC2實例,并使用terminate函數(shù)終止它們。
5. 實例化Python腳本
最后,您需要將上述代碼片段結(jié)合起來并實例化Python腳本,以便自動管理EC2實例。您可以使用像AWS Lambda這樣的服務(wù)自動運行Python腳本,或者使用計劃任務(wù)來定期運行它們。
import boto3import paramikoACCESS_KEY = 'YOUR_ACCESS_KEY'SECRET_KEY = 'YOUR_SECRET_KEY'REGION_NAME = 'us-west-2'ec2 = boto3.resource('ec2', aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY, region_name=REGION_NAME)def create_instance(): ec2.create_instances(ImageId='ami-0c55b159cbfafe1f0', MinCount=1, MaxCount=1, InstanceType='t2.micro', KeyName='my-key-pair')def configure_instance(): instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}]) instance_ids = [] for instance in instances: instance_ids.append(instance.id) for status in instance.state.values(): if status != 'running': print('Instance is not running') break for instance_id in instance_ids: instance = ec2.Instance(instance_id) ssh_client = paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_key = paramiko.RSAKey.generate(2048) ssh_key_file = 'my_key.pem' ssh_key.write_private_key_file(ssh_key_file) try: ssh_client.connect(hostname=instance.public_dns_name, username='ec2-user', pkey=ssh_key) stdin, stdout, stderr = ssh_client.exec_command('sudo yum update -y') print(stdout.read()) stdin, stdout, stderr = ssh_client.exec_command('sudo yum install -y httpd') print(stdout.read()) except ClientError as e: print(e) finally: ssh_client.close()def delete_instance(): instance_ids = [] instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}]) for instance in instances: instance_ids.append(instance.id) for status in instance.state.values(): if status != 'running': print('Instance is not running') break if not instance_ids: print('No running instances.') else: ec2.instances.filter(InstanceIds=instance_ids).terminate()if __name__ == '__main__': create_instance() configure_instance() delete_instance()
現(xiàn)在,您已經(jīng)了解了如何使用Python自動化配置AWS EC2實例。您可以將這些技術(shù)知識點應(yīng)用于您的實際應(yīng)用程序或服務(wù)并實現(xiàn)自動化。
以上就是IT培訓(xùn)機(jī)構(gòu)千鋒教育提供的相關(guān)內(nèi)容,如果您有web前端培訓(xùn),鴻蒙開發(fā)培訓(xùn),python培訓(xùn),linux培訓(xùn),java培訓(xùn),UI設(shè)計培訓(xùn)等需求,歡迎隨時聯(lián)系千鋒教育。