如何使用 boto3 获取我的 ec2 实例的 arn [英] How to get arn of my ec2 instance using boto3

查看:24
本文介绍了如何使用 boto3 获取我的 ec2 实例的 arn的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要我所有 ec2 实例的 arn.describe_instances() 没有给出实例.是否有任何其他方法或某种方式也可以列出所有 arn.我需要将它们存储在数据库中,而且我现在正在处理示例实例,这最终也需要适用于多个帐户.因此,一个始终有效的解决方案会很有帮助.

I want the arn of all my ec2 instances. The describe_instances() does not give out the instances. Is there any other method or some way that may list out all the arns as well. I need them to be stored in a database,also I'm working on sample instances for now,this eventually needs to work for multiple accounts as well. So, a solution that will work throughout will be helpful.

推荐答案

您可以自己重新创建:

arn:aws:ec2:::instance/

为此,我认为您甚至可以使用 * as 和 ,它会起作用.

For this purpose, I think you can even use * as and <ACCOUNT_ID>, and it will work.

有关更多信息,您可以查看此问题

for more info you can see this question

实际上,instance['Reservations'][0]['Instances'] 可能不是所有的实例.实例按安全组分组在一起.不同的安全组意味着将有许多列表元素.要获取该区域中的每个实例,您需要使用以下代码.

Actually instances['Reservations'][0]['Instances'] may not have all instances. Instances are grouped together by security groups.Different security groups means many list elements will be there. To get every instance in that region, you need to use the code below.

注意:['Reservations'][0]['Instances'] 没有列出所有的实例,它只给你按第一个安全组分组的实例.如果有很多组,您将无法获得所有实例.

Note: ['Reservations'][0]['Instances'] doesn't list all the instances, It only gives you the instances which are grouped by the first security group. If there are many groups you won't get all instances.

import boto3
region = 'ap-south-1'

ec2 = boto3.client('ec2', region_name=region)

def list_instances():
    instance_ids = []
    response = ec2.describe_instances(Filters=[{'Name': 'instance-type', 'Values': ["t2.micro", "t3.micro"]}])
    instances_full_details = response['Reservations']
    for instance_detail in instances_full_details:
        group_instances = instance_detail['Instances']

        for instance in group_instances:
            instance_id = instance['InstanceId']
            instance_ids.append(instance_id)
    return instance_ids

instance_ids = list_instances()
print(instance_ids)

这篇关于如何使用 boto3 获取我的 ec2 实例的 arn的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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