zoukankan      html  css  js  c++  java
  • Lambda 监控 AWS EC2 Ri到期时间

    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')

    邮件信息

    作者:Star-Hitian,转载请注明原文链接:https://www.cnblogs.com/Star-Haitian/p/14971944.html

  • 相关阅读:
    python面向对象的3个特点
    Redis-哈希槽
    PEP8 Python 编码规范
    每个人都要对自己进行5 项必要投资
    机器码和字节码
    python优缺点分析及python种类
    Zookeeper安装及运行
    Zookeeper简介与集群搭建
    Nginx Linux详细安装部署教程
    Nginx代理功能与负载均衡详解
  • 原文地址:https://www.cnblogs.com/Star-Haitian/p/14971944.html
Copyright © 2011-2022 走看看