python-3.x - 如何使用 Boto 3 显示 EC2 实例名称

标签 python-3.x amazon-web-services amazon-ec2 boto3 boto

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

打印(instance.id,instance.instance_type,region)这是有效的,但不是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)

最佳答案

您正在使用的实例对象没有名称属性。原因是实例的“名称”仅基于名为名称的标签。所以你必须获取标签,并找到一个标签名称为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)

关于python-3.x - 如何使用 Boto 3 显示 EC2 实例名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66363151/

相关文章:

bash - WGET 似乎不适用于 AWS EC2 启动时的用户数据

amazon-web-services - AWS ELB 或域 url 重定向到 EC2 实例公共(public) DNS

amazon-web-services - AWS : Deploying a stack using Cloud Formation with an existing Key Pair

python - 为什么我使用 Tag.models.all() 后 Taggit (Django-Tag) 就无法工作

python-3.x - python 3.6解释器中没有名为 `numpy`的模块

python - 用于检查元素是否在排序列表中的递归函数

amazon-ec2 - 如何在运行时更改实例类型

python-3.x - ImportError : libcublas. so.9.0:无法打开共享对象文件

python - Cloudfront URL 永不过期

django - 对 EC2 进行基准测试