Get list of EC2 instances with specific Tag and Va

2019-08-20 05:29发布

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)

2条回答
Root(大扎)
2楼-- · 2019-08-20 06:10

You are using the 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)
查看更多
Bombasti
3楼-- · 2019-08-20 06:11

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 . i.e.

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.

查看更多
登录 后发表回答