简体   繁体   中英

Get list of EC2 instances with specific Tag and Value in Boto3

How can I filter AWS instances using Tag and Value using boto3 ?

import boto3

ec2 = boto3.resource('ec2')
client = boto3.client('ec2')

response = client.describe_tags(
Filters=[{'Key': 'Owner', 'Value': 'user@example.com'}])
print(response)

You are using a wrong API. Use describe_instances

import boto3

client = boto3.client('ec2')

custom_filter = [{
    'Name':'tag:Owner', 
    'Values': ['user@example.com']}]
    
response = client.describe_instances(Filters=custom_filter)

boto3.client.describe_tags() is universal, but it is tedious to use. because you need to nest and specify the services, tag key name and tag values to filter . ie

client = boto3.client('ec2')
filters =[
    {'Name': 'resource-type', 'Values': ['instance']},
    {'Name': 'Key', 'Values': ['Owner']},
    {'Name': 'Values', 'Values' : ['user@example.com']}
]
response = client.describe_instances(Filters=filters)

As @helloV suggested, it is much easier to use describe_instances(). describe_tags is there to allow user to create function to traverse all the services tags.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM