【问题标题】:How to find the reservation_id for a ec2 instance using boto3如何使用 boto3 查找 ec2 实例的 reservation_id
【发布时间】:2016-07-29 00:54:22
【问题描述】:

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

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

一些代码

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

【问题讨论】:

    标签: boto3 aws-ec2


    【解决方案1】:
    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 信息并与正在运行的实例相关联。实例 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。预留实例计费将自动“应用”到具有确切容量的新 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

    注意:我只是在此处列出了所有实例的代码:To check whether AWS instance is up after reboot using python

    【讨论】:

      猜你喜欢
      • 2021-05-09
      • 2015-12-28
      • 2020-09-30
      • 1970-01-01
      • 2017-08-11
      • 1970-01-01
      • 2017-05-05
      • 2017-02-23
      • 2021-07-05
      相关资源
      最近更新 更多