【问题标题】:not getting all aws instances using python boto3 - problem with Reservation没有使用 python boto3 获取所有 aws 实例 - 保留问题
【发布时间】:2020-05-29 19:14:58
【问题描述】:

我编写了一个 python-boto3 脚本来从一个帐户和区域获取所有 aws 实例列表。

脚本运行良好,但没有给出所有实例。

例如,如果 n 个实例具有相同的 Reservation 编号,则仅在 Reservation 下获得一个实例。

请看下面的脚本,请帮助我如何获取所有 aws 实例列表,而不考虑预订号。

rg = 'us-west-2'
config = Config(
    retries = dict(
        max_attempts = 100
    )
)
ec = boto3.client('ec2', config=config, region_name=rg)

def get_tags():
    tag_list = []
    resp =  ec.describe_instances()['Reservations']
    #resp =  ec.describe_instances()
    #print(resp)
    tag_result = [['Name','InstanceId','State','t1:product','t1:environment-type','t1:environment-name']]
    for ec2 in resp:
    #for ec2 in resp["Reservation"]:
        #print(InstanceId)
        tag_list = []

【问题讨论】:

  • 感谢 john,我正在通过运行您的脚本获取所有实例列表。

标签: python-3.x amazon-web-services instance boto3


【解决方案1】:

在查看您的代码时,您要尝试做什么并不明显,但这里有一些代码遍历所有实例并显示它们的标签:

import boto3

ec2_client = boto3.client('ec2')

response = ec2_client.describe_instances()

for reservation in response['Reservations']:
    for instance in reservation['Instances']:
        print(instance['InstanceId'])
        for tag in instance['Tags']:
            print(tag['Key'], tag['Value'])

下面是使用 boto3 资源方法的等效代码:

import boto3

ec2_resource = boto3.resource('ec2')

for instance in ec2_resource.instances.all():
    print(instance.id)
    for tag in instance.tags:
        print(tag['Key'], tag['Value'])

请注意InstanceIdState 是实例对象上的可用目录。它们不是标签。

【讨论】:

  • 嗨约翰,谢谢你,我已经运行了你的脚本,它工作正常并且所有实例都正确。我想将输出导出到 excel 文件。 ,
  • 应该有一些 Python 库可以理解 Excel 文件格式,或者您可以简单地保存为 CSV 以加载到 Excel 中。如果您遇到问题,请随时创建另一个问题,详细说明您面临的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-07-14
  • 1970-01-01
  • 1970-01-01
  • 2019-03-10
  • 1970-01-01
  • 2018-08-09
  • 2017-02-27
相关资源
最近更新 更多