如何使用Boto显示EC2实例名



我使用下面的代码来显示instance_id,instance_type,但我无法显示我想要的实例名称

print (instance.id, instance.instance_type, region)this is working but this not instance.instance_name

import boto3
access_key = "AKIAJ5G2FAUVO3TXXXXXXXX"
secret_key = "nk7eytkWfoSDU0GwvBZVawQvXXXXXX"
client = boto3.client('ec2', aws_access_key_id=access_key, aws_secret_access_key=secret_key,region_name='us-east-1')
ec2_regions = [region['RegionName'] for region in client.describe_regions()['Regions']]
for region in ec2_regions:
conn = boto3.resource('ec2', aws_access_key_id=access_key, aws_secret_access_key=secret_key,region_name=region)
instances = conn.instances.filter()
for instance in instances:
if instance.state["Name"] == "running":
print (instance.instance_name,instance.id, instance.instance_type, region)

您正在使用的instance对象没有name属性。原因是"名称"。在一个实例中,只有基于标签称为Name。因此,您必须获得标签,并找到Name的标签名称:

def get_tag(tags, key='Name'):
if not tags: return ''
for tag in tags:

if tag['Key'] == key:
return tag['Value']

return ''
ec2_regions = [region['RegionName'] for region in client.describe_regions()['Regions']]
for region in ec2_regions:
conn = boto3.resource('ec2', aws_access_key_id=access_key, aws_secret_access_key=secret_key,region_name=region)
instances = conn.instances.filter()
for instance in instances:
instance_name = get_tag(instance.tags)        
print (instance_name, instance.id, instance.instance_type, region)

相关内容

  • 没有找到相关文章

最新更新