Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/amazon-web-services/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何使用Boto 3显示EC2实例名称_Python 3.x_Amazon Web Services_Amazon Ec2_Boto3_Boto - Fatal编程技术网

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

Python 3.x 如何使用Boto 3显示EC2实例名称,python-3.x,amazon-web-services,amazon-ec2,boto3,boto,Python 3.x,Amazon Web Services,Amazon Ec2,Boto3,Boto,我正在使用下面的代码来显示instance_id,instance_type,但是我无法显示我想要的实例名称 打印(instance.id,instance.instance\u类型,区域)这正在工作,但不是instance.instance\u名称 import boto3 access_key = "AKIAJ5G2FAUVO3TXXXXXXXX" secret_key = "nk7eytkWfoSDU0GwvBZVawQvXXXXXX" client

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

打印(instance.id,instance.instance\u类型,区域)
这正在工作,但不是instance.instance\u名称

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
的标记。因此,您必须获取标记,并找到标记名
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)


您可以检查boto3文档,或者如果您可以使用PDB,只需调试它并使用dir(实例)列出属性谢谢,sir代码工作正常,但下面显示了错误alsofor tag in tags:TypeError:“NoneType”对象不是iterableI我是一个非python的人,所以请在此帮助我非常感谢,先生,祝你今天愉快ahead@aviraldb没问题。很高兴它成功了:-)