【问题标题】:How to check the Aws ec2 Instance runtime in hours using lambda如何使用 lambda 在几小时内检查 Aws ec2 实例运行时
【发布时间】:2022-01-16 08:59:30
【问题描述】:

如何获取 AWS Ec2 Instance 的运行时间超过 4 小时?

我在这里尝试过:

import boto3
ec2 = boto3.resource('ec2', region_name='instance_region_name')
volume = ec2.Volume('vol-id')
print volume.create_time.strftime("%Y-%m-%d %H:%M:%S")

【问题讨论】:

    标签: python amazon-web-services amazon-ec2 aws-lambda


    【解决方案1】:

    我正在使用下面的代码。我还需要检查具有公共 ip 的实例。

    import boto3
    from datetime import datetime, timezone, timedelta
    from botocore.exceptions import ClientError
    
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    
    ec2_resource = boto3.resource('ec2', region_name='instance_region_name')
    
    instances = ec2_resource.instances.filter(Filters=[{
        'Name': 'instance-state-name',
        'Values': ['running']
    }])
    
    for instance in instances:
        names = [x['Value'] for x in instance.tags if x['Key'] == 'Name']
        if len(names) > 0:
            name = names[0]
        else:
            name = ''
        uptime = datetime.now(timezone.utc) - instance.launch_time
        print(name, instance.id, instance.public_ip_address, instance.key_name,
                name, uptime)
        if (not (instance.public_ip_address is None) and uptime > timedelta(hours=4)):
            logger.info('Public instance %s is running for %s', instance.id,
                        uptime)
    

    【讨论】:

      猜你喜欢
      • 2016-06-01
      • 2017-05-28
      • 1970-01-01
      • 1970-01-01
      • 2016-08-20
      • 2020-06-24
      • 2020-09-29
      • 1970-01-01
      • 2021-05-30
      相关资源
      最近更新 更多