不能使用python boto3获取所有aws实例-保留问题 [英] not getting all aws instances using python boto3 - problem with Reservation

查看:147
本文介绍了不能使用python boto3获取所有aws实例-保留问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了python-boto3脚本,以从帐户和区域获取所有aw实例列表.

I have written a python-boto3 script to get all aws instances list from an account and region.

脚本运行正常,但未提供所有实例.

the script is running fine, but not giving all instances.

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

for example ,if n instances are with same Reservation number then getting only one instance under Reservation.

请看下面的脚本,请帮我如何获取所有AWS实例列表,而不管预订号如何.

please look at the below script , please help me how can I get all aws instances list irrespective of reservation number.

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 = []

推荐答案

在查看您的代码时,您要执行的操作并不明显,但是下面的代码遍历了所有实例并显示了它们的标签:

In looking at your code, it's not obvious what you're trying to do, but here's some code that goes through all instances and shows their tags:

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资源方法的等效代码:

Here's the equivalent code using the boto3 resource method:

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是实例对象上的可用目录.它们不是标签.

Please note that InstanceId and State are available directory on the instances object. They are not Tags.

这篇关于不能使用python boto3获取所有aws实例-保留问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆