如何使用 boto3 找到 ec2 实例的 reservation_id

How to find the reservation_id for a ec2 instance using boto3

原因:我正在处理类似于 AWS 提供的预留利用率报告的报告(但不同)

我有实例列表。
我有我的预订清单。
我想 link 他们了。我知道许多实例可能共享相同的保留。但是我应该能够 link 它们,但只有我知道特定实例的 reservation_id 。但是...如何获取实例的 reservation_id????检查文档,只能找到 cmd 行工具来获取此信息。

一些代码

import boto3
client = boto3.client('ec2')
region = "us-east-1"  
ec2 = boto3.resource("ec2", region_name=region)  
ec2_list = list()
for instance in ec2.instances.all():
    name = 'Un-named'
    for tag in instance.tags:
        if tag['Key'].upper() == 'NAME':
            name = tag['Value']   # nothing called tag['reservation_id']
ec2_list.append((name, instance.id, instance.public_dns_name,
                 instance.placement['AvailabilityZone'],
                 instance.instance_type))

reservations = client.describe_reserved_instances()
import boto3
ec2 = boto3.client("ec2") 
response = ec2.describe_instances() 

for each_reservation in response["Reservation"]: 
    for each_instance in each_reservation["Instances"])
        print("Reserved_id:{}\tinstance_id:{}".format(
            each_reservation["ReservationId"],
            each_instance["InstanceId"])) 

(更新) 我刚刚意识到 OP 可能会询问映射 reserved instances 信息并与 运行ning 实例相关联。实例 ReservationId 实际上与保留实例无关。

不幸的是,这很复杂。因为 AWS 会自动集中使用与确切实例容量和可用区匹配的保留实例。当保留实例用完时,计费将从典型的按需实例开始。

所以有很多基于转换的混合匹配计费。例如:

  1. 您刚刚在 us-west-1 运行 启动了一个 EC2 c4.large 3 天 (0.105 x 3 24)
  2. 对容量很满意,现在想用它来生产。您只需在 us-west-1 中为 c4.large 创建预留实例请求,预付 1 年($576)。
  3. 年中,在 us-west-1 下创建了另一个 c4.large 12 小时。您将按按需费率收费。
  4. 然后你关闭了之前的EC2。预留实例计费将自动 "apply" 到具有准确容量的新 EC2。

如您所见,目前无法与 boto3 建立这种计费动态关联。

由于预付款,人们希望检查未使用的保留,有人已经创建了一个 boto 包到:check any idle reserved instances。这个包很方便,因为有些用户可能会在一个 AZ 中为保留实例付费,但不小心将 EC2 放在另一个 AZ 中,等等。

(以下部分留作历史阅读)

boto3.client("ec2").describe_instances() 和 boto3.resource("ec2").instances.filter() 将完成这项工作.只需选择其中之一。无需预订处理。 http://boto3.readthedocs.org/en/latest/reference/services/ec2.html#EC2.Client.describe_instances

除非你使用"MaxResults"和"NextToken"来控制输出,否则describe_instances()会显示所有实例。

如果你查看 boto3 文档,他们会告诉你这个。 http://boto3.readthedocs.org/en/latest/guide/migrationec2.html

注意:我只是在此处列出了所有实例的代码: