携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第20天,点击查看活动详情
1.定义ec2 client
1.1 首先导入boto3的包
import boto3
1.2 定义ec2 client
import boto3
from botocore.config import Config #导入配置模块
# 在这里定义ec2的client,并且使用Config来设置区域
ec2 = boto3.client('ec2',config=Config(region_name='us-east-1'))
2.对EC2进行描述操作(列出)
2.1 请求语法
response = client.describe_instances(
Filters=[
{
'Name': 'string',
'Values': [
'string',
]
},
],
InstanceIds=[
'string',
],
DryRun=True|False,
MaxResults=123,
NextToken='string'
)
2.2 列出所有实例
import boto3
from botocore.config import Config #导入配置模块
# 在这里定义ec2的client,并且使用Config来设置区域
ec2 = boto3.client('ec2',config=Config(region_name='us-east-1'))
# 定义 list_all_ins 来接收ec2 client请求的返回数据
list_all_ins = ec2.describe_instances()
# 使用print进行打印
print(list_all_ins)
2.3 列出指定实例,以id作为参数
import boto3
from botocore.config import Config #导入配置模块
# 在这里定义ec2的client,并且使用Config来设置区域
ec2 = boto3.client('ec2',config=Config(region_name='us-east-1'))
# 在下面的请求中,添加了一个InstanceIds的数组,其中 'i-1234657801' 就是某个实例的id,那么这个请求只会返回该实例的相关信息,而不是打印所有
list_all_ins = ec2.describe_instances(
InstanceIds=[
'i-12345678901',
],
)
# 使用print进行打印
print(list_all_ins)
3.对EC2开机、关机或终止
3.1 请求语法
# 开机语法
# InstanceIds (list) [REQUIRED]
response = client.start_instances(
InstanceIds=[
'string',
],
AdditionalInfo='string',
DryRun=True|False
)
# 关机语法
# InstanceIds (list) [REQUIRED]
response = client.stop_instances(
InstanceIds=[
'string',
],
Hibernate=True|False,
DryRun=True|False,
Force=True|False
)
# 终止实例
# InstanceIds (list) [REQUIRED]
response = client.terminate_instances(
InstanceIds=[
'string',
],
DryRun=True|False
)
3.2 启动实例例子
import boto3
from botocore.config import Config #导入配置模块
# 在这里定义ec2的client,并且使用Config来设置区域
ec2 = boto3.client('ec2',config=Config(region_name='us-east-1'))
# 在下面的请求中,添加了一个InstanceIds的数组,其中 'i-1234657801' 就是某个实例的id
start_ins = ec2.start_instances(
InstanceIds=[
'i-12345678901',
]
)
# 使用print进行打印,这里会返回实例的状态, pending
print(start_ins)
3.3 关闭实例例子
import boto3
from botocore.config import Config #导入配置模块
# 在这里定义ec2的client,并且使用Config来设置区域
ec2 = boto3.client('ec2',config=Config(region_name='us-east-1'))
# 在下面的请求中,添加了一个InstanceIds的数组,其中 'i-1234657801' 就是某个实例的id
stop_ins = ec2.stop_instances(
InstanceIds=[
'i-12345678901',
]
)
# 使用print进行打印,这里会返回实例的状态, stopping
print(stop_ins)
3.4 终止实例例子
import boto3
from botocore.config import Config #导入配置模块
# 在这里定义ec2的client,并且使用Config来设置区域
ec2 = boto3.client('ec2',config=Config(region_name='us-east-1'))
# 在下面的请求中,添加了一个InstanceIds的数组,其中 'i-1234657801' 就是某个实例的id
terminate_ins = ec2.terminate_instances(
InstanceIds=[
'i-12345678901',
]
)
# 使用print进行打印,这里会返回实例的状态, stopping
print(terminate_ins)
4.创建EC2 Tags或重写Tags
4.1 请求语法
创建和重写都是用的一个api
Resourcesb(list) -- [REQUIRED]
Tags (list) -- [REQUIRED]
response = client.create_tags(
DryRun=True|False,
Resources=[
'string',
],
Tags=[
{
'Key': 'string',
'Value': 'string'
},
]
)
4.2 创建Tag
import boto3
from botocore.config import Config #导入配置模块
# 在这里定义ec2的client,并且使用Config来设置区域
ec2 = boto3.client('ec2',config=Config(region_name='us-east-1'))
# 定义一个列表 tagkv ,里面包含字典
tagkv = [{"Key":"Name","Value":"Demo"}]
# 下面 InstanceIds 为 ['i-12346579801'], 然后将tagkv进行传递
create_tags_resp = self.client.create_tags(
Resources=[
'i-12345678901',
],
Tags=tagkv
)
4.3 重写Tag
在上面的基础上,重写Tag Name的值
import boto3
from botocore.config import Config #导入配置模块
# 在这里定义ec2的client,并且使用Config来设置区域
ec2 = boto3.client('ec2',config=Config(region_name='us-east-1'))
# 定义一个列表 tagkv ,里面包含字典
tagkv = [{"Key":"Name","Value":"NewDemo"}]
# 下面 InstanceIds 为 ['i-12346579801'], 然后将tagkv进行传递
create_tags_resp = self.client.create_tags(
Resources=[
'i-12345678901',
],
Tags=tagkv
)
5.删除EC2 Tags
5.1 请求语法
Resourcesb(list) -- [REQUIRED]
response = client.delete_tags(
DryRun=True|False,
Resources=[
'string',
],
Tags=[
{
'Key': 'string',
'Value': 'string'
},
]
)
5.2 删除示例
import boto3
from botocore.config import Config #导入配置模块
# 在这里定义ec2的client,并且使用Config来设置区域
ec2 = boto3.client('ec2',config=Config(region_name='us-east-1'))
# 定义一个列表 tagkv ,里面包含字典
tagkv = [{"Key":"Name","Value":"NewDemo"}]
# 下面 InstanceIds 为 ['i-12346579801'], 然后将tagkv进行传递
delete_tags = ec2.delete_tags(
Resources=[
'i-12345678901',
],
Tags=tagkv
)
6.EC2类示例
import boto3
from botocore.config import Config
class Ec2:
def __init__(self, region):
self.ins_id = None
self.client = boto3.client('ec2', config=Config(region_name=region))
self.region = region
# 返回指定的字段
def list_ins(self):
list_ins_resp = self.client.describe_instances()
self.ins = []
print(list_ins_resp['Reservations'])
for i in range(len(list_ins_resp['Reservations'])):
ins_info = {}
ins_tags_list = []
tag_dic = {}
tp_list = list_ins_resp['Reservations'][i]['Instances'][0]
ins_info['_id'] = tp_list['InstanceId']
ins_info['state'] = tp_list['State']['Name']
ins_info['zone'] = tp_list['Placement']['AvailabilityZone']
if 'PublicIpAddress' in tp_list:
ins_info['pv_ip'] = tp_list['PrivateIpAddress']
else:
ins_info['pv_ip'] = ''
if 'PublicIpAddress' in tp_list:
ins_info['pu_ip'] = tp_list['PublicIpAddress']
else:
ins_info['pu_ip'] = ''
self.ins.append(ins_info)
return {
'headers': {
"Content-Type": "application/json"
},
'statusCode': 200,
'body': self.ins
}
def enable_ins(self, ins_id):
self.ins_id = ins_id
start_ins_resp = self.client.start_instances(
InstanceIds=[
self.ins_id,
]
)
return start_ins_resp['StartingInstances'][0]['CurrentState']['Name']
def disable_ins(self, ins_id):
self.ins_id = ins_id
stop_ins_resp = self.client.stop_instances(
InstanceIds=[
self.ins_id,
],
Force=True
)
return stop_ins_resp['StoppingInstances'][0]['CurrentState']['Name']
def terminate_ins(self, ins_id):
self.ins_id = ins_id
terminate_ins_resp = self.client.terminate_instances(
InstanceIds=[
self.ins_id,
],
DryRun=True
)
return terminate_ins_resp['TerminatingInstances'][0]['CurrentState']['Name']
def create_tags(self, ins_id, tagkv):
self.ins_id = ins_id
create_tags_resp = self.client.create_tags(
Resources=[
self.ins_id,
],
Tags=tagkv
)
return {
'headers': {"Content-Type": "application/json"},
'statusCode': 200,
}
def delete_tags(self, ins_id, tagkv):
self.ins_id = ins_id
delete_tags_resp = self.client.delete_tags(
Resources=[
self.ins_id,
],
Tags=tagkv
)
return {
'headers': {"Content-Type": "application/json"},
'statusCode': 200,
}