这里使用python SDK boto3
,文档:
https://aws.amazon.com/sdk-for-python/
https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html
¶ 安装
pip3 install boto3
¶ 配置
cd
mkdir .aws
vim ~/.aws/credentials
[default]
aws_access_key_id = YOUR_ACCESS_KEY
aws_secret_access_key = YOUR_SECRET_KEY
region=ap-northeast-1
然后进入AWS EC2 console,点击右上角的下拉框,点击里面的security credentials,在里面创建access key和对应的secret key,其中secret key只在创建的时候显示,一定要妥善保存,丢失后只能再创建一个新的。
¶ EC2 client
官方示例:https://boto3.amazonaws.com/v1/documentation/api/latest/guide/ec2-example-managing-instances.html
import boto3
= boto3.client('ec2') client
下面介绍一些常用的。
¶ describe_instances
import json5
= client.describe_instances(
response =[
InstanceIds1],
sys.argv[
],
)print(json5.dumps(
response,=4,
indent# https://stackoverflow.com/a/36142844/13688160
=str
default ))
¶ 打印private IP
= client.describe_instances(
response =[
InstanceIds1],
sys.argv[
],
)= response['Reservations']
response assert len(response) == 1
= response[0]
response = response['Instances']
instances assert len(instances) == 1
= instances[0]
instance print(instance['PrivateIpAddress'])
¶ 打印instance个数
= client.describe_instances(
response =[
Filters
{'Name': 'instance-state-name',
'Values': [
'pending',
'running',
'shutting-down',
'stopping',
'stopped',
]
},
],
)= response['Reservations']
reservations print(len(reservations))
for reservation in reservations:
assert len(reservation['Instances']) == 1
¶ run_instances
创建实例。
= client.run_instances(
response =[
BlockDeviceMappings
{'DeviceName': '/dev/nvme0n1',
'Ebs': {
'DeleteOnTermination': True,
'Iops': 16000,
'VolumeSize': 512, # GiBs
'VolumeType': 'gp3',
'Throughput': 600, # MiB/s
'Encrypted': False
},
},
],='ami-08c2888d01ed84209', # Debian 12
ImageId='i4i.2xlarge',
InstanceType='string',
KeyName=1,
MinCount=1,
MaxCount=[
SecurityGroupIds'string',
],=[
TagSpecifications
{'ResourceType': 'instance',
'Tags': [
{'Key': 'Name',
'Value': '实例名',
},
],
},
],=True,
EbsOptimized
)assert len(response['Instances']) == 1
= response['Instances'][0]
instance print(instance['InstanceId'])
但是似乎不能设置hostname。
在使用前先用下面介绍的wait_until_exists
等待instance成功创建,不然会报instance不存在的错误。
¶ Instance
import boto3
= boto3.resource('ec2')
ec2 = ec2.Instance('id') instance
¶ wait_until_exists
instance.wait_until_exists()
¶ wait_until_running
来源:https://stackoverflow.com/questions/19054081/ec2-waiting-until-a-new-instance-is-in-running-state
¶ terminate_instances
client.terminate_instances(=[
InstanceIds'string',
], )