[英]List AWS instances by Tag Name using python
我有小的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)
您需要遍歷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)
我們可以用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.