环境准备
pip install boto3
Alternatively, you can create the credential file yourself. By default, its location is at ~/.aws/credentials
:
[default]
aws_access_key_id = YOUR_ACCESS_KEY
aws_secret_access_key = YOUR_SECRET_KEY
You may also want to set a default region. This can be done in the configuration file. By default, its location is at ~/.aws/config
:
[default]
region=us-east-1
除了以上配置以外,还可以用环境变量,参数指定等等方式来配置验证
脚本实例
#/usr/bin/python
#coding:utf-8
#2021年2月22日09:47:13
#统计EC2和RDS的所有信息,并计算实例个数
#############################
import boto3
import json
import datetime
import dateutil.parser
import decimal
from collections import defaultdict
class MyJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, (datetime.datetime,)):
return obj.isoformat()
elif isinstance(obj, (decimal.Decimal,)):
return str(obj)
else:
return super().default(obj)
# 统计EC2
def get_ec2_info():
ec2 = boto3.client('ec2')
response = ec2.describe_instances()
instance_info_list=[]
for i in response['Reservations']:
for j in i['Instances']:
instance_info = {}
instance_info['PublicDnsName'] = j['PublicDnsName'] or ''
instance_info['State'] = j['State']['Name']
instance_info['LaunchTime'] = json.dumps(j['LaunchTime'],cls=MyJSONEncoder)
instance_info['PublicIpAddress'] = j['PublicIpAddress'] if j.get('PublicIpAddress') else ''
instance_info['PrivateIpAddress'] = j['PrivateIpAddress']
instance_info['VpcId'] = j['VpcId']
instance_info['InstanceId'] = j['InstanceId']
instance_info['InstanceType'] = j['InstanceType']
instance_info['AvailabilityZone'] = j['Placement']['AvailabilityZone']
instance_info_list.append(instance_info)
return instance_info_list
# 统计RDS
def get_rds():
rds = boto3.client('rds')
rds_info_list = []
re =rds.describe_db_instances()
for i in re['DBInstances']:
rds_info={}
rds_info['InstanceCreateTime']=i['InstanceCreateTime']
rds_info['Engine']=i['Engine']
rds_info['DBInstanceArn']=i['DBInstanceArn'] if i.get('DBInstanceArn') else ''
rds_info['DBInstanceStatus']=i['DBInstanceStatus']
rds_info['Port']=i['Endpoint']['Port']
rds_info['Address']=i['Endpoint']['Address']
rds_info['DBInstanceIdentifier']=i['DBInstanceIdentifier']
rds_info['DBInstanceClass']=i['DBInstanceClass']
rds_info['AvailabilityZone']=i['AvailabilityZone']
rds_info_list.append(rds_info)
if re.get('Marker'):
mark=re.get('Marker')
while mark:
re1=rds.describe_db_instances(Marker=mark)
for i in re1['DBInstances']:
rds_info={}
rds_info['InstanceCreateTime']=i['InstanceCreateTime']
rds_info['Engine']=i['Engine']
rds_info['DBInstanceArn']=i['DBInstanceArn'] if i.get('DBInstanceArn') else ''
rds_info['DBInstanceStatus']=i['DBInstanceStatus']
rds_info['Port']=i['Endpoint']['Port']
rds_info['Address']=i['Endpoint']['Address']
rds_info['DBInstanceIdentifier']=i['DBInstanceIdentifier']
rds_info['DBInstanceClass']=i['DBInstanceClass']
rds_info['AvailabilityZone']=i['AvailabilityZone']
rds_info_list.append(rds_info)
if re1.get('Marker'):
mark=re.get('Marker')
else:
mark=False
return rds_info_list
else:
return rds_info_list
#print(json.loads(response,object_hook=object_hook))
#print(json.dumps(response,cls=MyJSONEncoder))
if __name__ == '__main__':
default_dict = defaultdict(int)
ec2_list=get_ec2_info()
for instance in ec2_list:
default_dict[instance['InstanceType']] +=1
print('\033[1;32mEC2信息:\033[0m')
print default_dict
for k,v in default_dict.items():
print k,":",v
dblist = get_rds()
rds_dict = defaultdict(int)
for db in dblist:
rds_dict[db['DBInstanceClass']] +=1
print('\033[1;32mRDS信息:\033[0m')
print rds_dict
for k,v in rds_dict.items():
print k,":",v
该脚本只需要把收集到的数据整理下,按自己需要的格式保存到CMDB中即可。