我有一个小的python代码,用于列出跨地区的所有EC2实例,但我找不到如何获取Tag' Name'而我正在打印结果。 使用instance.tags打印所有标签,但我只想要' Name'
代码示例:
import boto3
access_key = "xyw"
secret_key = "xywz"
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 (region, instance.key_name, instance.public_dns_name, instance.image_id, instance.instance_type, instance.tags)
答案 0 :(得分:0)
您需要遍历tags
,因此您需要在代码中添加此内容
for tag in tags:
if tag["Key"] == 'Name':
instancename = tag["Value"]
类似这样的事情
import boto3
access_key = "xyw"
secret_key = "xywz"
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":
instancename = ''
for tag in instance.tags:
if tag["Key"] == 'Name':
instancename = tag["Value"]
print (region, instance.key_name, instance.public_dns_name, instance.image_id, instance.instance_type, instancename)
答案 1 :(得分:0)
我们可以使用boto'
get_all_instances
可以将标签作为过滤器
参考:http://boto.cloudhackers.com/en/latest/ref/ec2.html
def list_nodes():
filter_tags = {
"tag:Environment": "xyz",
"tag:Project": "abc",
"tag:Test": "test",
"instance-state-name": 'running'
}
boto_ec2 = EC2Connection(..)
reservations = boto_ec2.get_all_instances(filters=filter_tags)
instances = [i for r in reservations for i in r.instances]
return instances