获取终止的 EC2 实例的 ID

Get Ids of terminated EC2 instances

我正在尝试创建一份关于我们的 EC2 实例使用情况和利用率的报告。我想检查过去 X 天在我的环境中已经或曾经 运行 的所有实例。作为报告的一部分,我想包括在规模组扩展期间创建但后来在组扩展时终止的实例。

使用带有 boto3 的简单 python 脚本,我可以获得区域的实例列表:

session = Session(aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY, region_name=self.name)
ec2 = session.resource('ec2')
cloudwatch = session.resource('cloudwatch')

通过使用以下命令列出实例,几个小时后我没有看到终止的实例(可能与您在仪表板中停止看到它们的时间相同):

ec2.instances.all()

使用 cloudwatch,当我使用以下命令时,我确实看到了已终止实例的指标:

metric = cloudwatch.Metric('AWS/EC2', 'CPUUtilization')
result = metric.get_statistics(
Dimensions=[{'Name': 'InstanceId', 'Value': instanceId}],
        StartTime=timeRange.start,
        EndTime=timeRange.end,
        Period=300,
        Statistics=['Average'],
) # This returns a complete list of data points for the instance was live

这意味着终止实例确实存在指标,但您必须拥有这些实例的 ID 才能检索它们。 有没有办法检索已终止的实例 ID?

除非您启用了 CloudTrail,否则不会。您可以从 CloudTrail 仪表板获取您想要的最近 7 天的信息。如果您需要超过 7 天的信息,请从 S3 存储桶中获取文件(如果您已配置)。

CloudTrail 定期将您的 activity 作为对象存储在您的存储桶中 - 检查您的 CloudTrail 配置以获取存储桶名称。数据每天存储为压缩 json 文件。编写一个简单的 Python 脚本来下载你想要的那一天的文件并一个一个地加载 json 文件,寻找 TerminatedInstances 事件。对于每个终止的实例,它都会包含诸如 instanceid、终止者、从何处、何时等信息,

代码片段:

for event in events:
    if event['eventName'] == 'TerminateInstances':
        inst_ids = [item['instanceId'] for item in event['requestParameters']['instancesSet']['items']]
        print 'Terminated instance IDs:', inst_ids

您可以使用 instance-state-name:

The state of the instance (pending | running | shutting-down | terminated | stopping | stopped ).

ec2 = boto3.client('ec2')
reservations = ec2.describe_instances(Filters=[
    {
        "Name": "instance-state-name",
        "Values": ["terminated"],
    }
]).get("Reservations")

for reservation in reservations:
    for instance in reservation["Instances"]:
        instance_id = instance["InstanceId"]