AWS Python Boto3 - 通过id获取实例运行时间

问题描述 投票:0回答:2

我正在尝试使用python boto3库为aws找到实例已经启动的分钟数。我无法找到直接的方法来做到这一点。我可以使用以下方式获取机器的状态:

ec2 = boto3.resource('ec2')
instance = ec2.Instance(instance_id)

status = instance.state['Name']
print(status)

但我正在寻找的是一个简单的指标:实例运行的分钟数。请注意,这不是实例的正常运行时间,因为它会在停止时重置。

python amazon-web-services amazon-ec2 aws-sdk boto3
2个回答
1
投票

这是一个你可以尝试的想法。查询“RunInstance”,“StopInstance”和“StartInstance”的CloudTrail数据计算实例的总运行时间。

这是我创建的脚本。 https://gist.github.com/sudharsans/990dbb67f397d79556dbc02e5835e5ec

样本输出:

i-0xxxxxfcd40ebd6a1 user 0:09:21.263278
i-xxxxxx502450c96aa yser 84 days, 15:13:37.651975
i-xxxxxxfcdf27ec894 yser 6 days, 15:43:52.191147
i-xxxxx386c630af322 user 13 days, 14:08:49.429469
i-xxxxxxxd41bf975eb test 21:37:59.67100

0
投票

我最终创建了另一个每分钟运行的lambda函数,如果实例正在运行,它会增加存储在dynamodb中的值。不是一个很好的解决方案,但这很有效。

import boto3
import time

def lambda_handler(event, context):
    dynamodb = boto3.resource('dynamodb', region_name='us-east-1', endpoint_url="https://dynamodb.us-west-1.amazonaws.com")
    table = dynamodb.Table('<table name>')

    response = table.scan()
    data = response['Items']

    for i in data:
        state = get_state(i['instance_id'])
        if (state=='running'):
            response = table.update_item(
                Key={
                'id': i['id']
                },
                UpdateExpression="set runTime = :r",
                ExpressionAttributeValues={
                ':r': i['runTime'] + 1,
                },
                ReturnValues="UPDATED_NEW"
            )

    return response

def get_state(instance_id):
    ec2 = boto3.resource('ec2')
    instance = ec2.Instance(instance_id)
    return instance.state['Name']
© www.soinside.com 2019 - 2024. All rights reserved.