「Python3」关于AWS SDK API

「Python3」关于AWS SDK API

四月 19, 2019

aws官方有提供Python接口:
https://boto3.amazonaws.com/v1/documentation/api/latest/index.html

这几天小试牛刀写了一个获取AWS EC2信息的脚本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import boto3

aws_key = 'XXX'
aws_secret = 'XXX'
aws_region = 'XXX'
session = boto3.session.Session(aws_access_key_id=aws_key, aws_secret_access_key=aws_secret, region_name=aws_region)

#获取预留实例信息
'''
ec2_client = session.client('ec2')
reserved_instances = ec2_client.describe_reserved_instances()
for reserved_instance in reserved_instances['ReservedInstances']:
print(reserved_instance['ReservedInstancesId'],reserved_instance['InstanceType'],reserved_instance['ProductDescription'],reserved_instance['State'],reserved_instance['Start'],reserved_instance['End'],reserved_instance['RecurringCharges'],reserved_instance['InstanceCount'])
'''
#获取实例信息
ec2_resource = session.resource('ec2')
ec2_list = []
for instance in ec2_resource.instances.all():
ec2_server = {}
# ec2_name = list(enumerate(instance.tags))
# print(ec2_name)
ec2_Name_index = [i for i, x in enumerate(instance.tags) if x['Key'].find('Name') == 0]
# print(ec2_Name_index)
# name = []
# for i, x in enumerate(instance.tags):
# if x['Key'].find('Name') == 0:
# name.append(i)
# print(name)
ec2_Service_index = [i for i, x in enumerate(instance.tags) if x['Key'].find('Service') == 0]
# print(ec2_Service_index)
ec2_server['id'] = instance.id
ec2_server['ip'] = instance.private_ip_address
ec2_server['hostname'] = instance.tags[ec2_Name_index[0]]['Value']
ec2_server['port'] = '22'
ec2_server['Server'] = instance.tags[ec2_Service_index[0]]['Value']
ec2_list.append(ec2_server)
print(ec2_list)