Lambda
1 import boto3
2 import datetime
3
4 client = boto3.client('ec2', )
5 alias = boto3.client('iam').list_account_aliases()['AccountAliases'][0]
6 regions = [region['RegionName'] for region in client.describe_regions()['Regions']]
7
8
9 def get_ri(regions, file):
10 global alias
11 with open(file, 'w', encoding='utf-8') as f:
12
13 for region in regions:
14 print(region)
15 ec2 = boto3.client('ec2', region_name=region,)
16 reserved_instances = ec2.describe_reserved_instances()
17 for reserved_instance in reserved_instances['ReservedInstances']:
18 state = reserved_instance['State']
19 endtimestr = str(reserved_instance['End']).split('+')[0]
20 endtime = datetime.datetime.strptime(endtimestr, '%Y-%m-%d %H:%M:%S')
21 timedif = (endtime - datetime.datetime.now()).days
22 if state == "active" and timedif <= 15:
23 msg = f'''
24 alias: {alias}
25 region: {region}
26 ReservedInstancesId: {reserved_instance['ReservedInstancesId']},
27 InstanceType: {reserved_instance['InstanceType']},
29 state: {reserved_instance['State']},
30 Start: {reserved_instance['Start']},
31 End: {reserved_instance['End']},
32 InstanceCount: {reserved_instance['InstanceCount']}
33 '''
34 f.write(msg)
35 print(msg)
36
37 def sends_sns(file):
38 client = boto3.client('sns', region_name='cn-northwest-1',
39 aws_access_key_id='AKIAQG4I2NOISOTWQG45',
40 aws_secret_access_key='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', )
41 try:
42 with open(file, 'r', encoding='utf-8') as f:
43 msg = f.read()
44 if msg:
45 response = client.publish(
46 TargetArn='arn:aws-cn:sns:cn-northwest-1:014782458769:UnitAlarm',
47 Message=msg,
48 )
49 except FileNotFoundError:
50 pass
51
52
53
54 def lambda_handler(event, context):
55 # TODO implement
56 file = '/tmp/ri_test.txt'
57 get_ri(regions, file)
58 sends_sns(file)
59
60
61 # if __name__ == '__main__':
62 # lambda_handler(event='txt', context='test')
邮件信息