使用 Boto 3 显示 EC2 实例名称

问题描述 投票:0回答:3

我不确定如何使用

boto3

在 AWS EC2 中显示我的实例名称

这是我的一些代码:

import boto3

ec2 = boto3.resource('ec2', region_name='us-west-2')
vpc = ec2.Vpc("vpc-21c15555")
for i in vpc.instances.all():
    print(i)

我得到的回报是

...
...
...
ec2.Instance(id='i-d77ed20c')

我可以将

i
更改为
i.id
i.instance_type
但当我尝试
name
我得到:

AttributeError: 'ec2.Instance' object has no attribute 'name'

获取实例名称的正确方法是什么?

python python-3.x amazon-web-services amazon-ec2 boto3
3个回答
27
投票

可能还有其他方法。但从您的代码角度来看,以下内容应该有效。

>>> for i in vpc.instances.all():
...   for tag in i.tags:
...     if tag['Key'] == 'Name':
...       print tag['Value']

如果你想使用 Python 强大的列表理解,一个线性解决方案:

inst_names = [tag['Value'] for i in vpc.instances.all() for tag in i.tags if tag['Key'] == 'Name']
print inst_names

7
投票

在 AWS EC2 中,实例带有名称 tag 标记

为了获取给定实例的名称标签的值,您需要查询该标签的实例:

请参阅 使用 boto 从 AWS 实例获取标签


0
投票

获取 current 实例(脚本正在运行的位置)的名称:

import requests
import boto3

session = boto3.Session(aws_access_key_id='...', aws_secret_access_key='...')
ec2 = session.client('ec2', region_name='...')
rid = requests.get('http://169.254.169.254/latest/meta-data/instance-id').text
tags = ec2.describe_tags(Filters=[{'Name': 'resource-id', 'Values': [rid]}])
print(tags['Tags'][0]['Value'])
© www.soinside.com 2019 - 2024. All rights reserved.