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

25,997

Solution 1

You are using a wrong API. Use describe_instances

import boto3

client = boto3.client('ec2')

custom_filter = [{
    'Name':'tag:Owner', 
    'Values': ['[email protected]']}]
    
response = client.describe_instances(Filters=custom_filter)

Solution 2

Instance with tags and instances without tags can be retrieved as below Can get all tags as below

import boto3

ec2 = boto3.resource('ec2',"us-west-1")
instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])
for instance in instances:
    if instance.tags != None:
        for tags in instance.tags:
        if tags["Key"] == 'Name' or tags["Key"] == 'Owner':
            if tags["Key"] == 'Name':
                instancename = tags["Value"]
            if tags["Key"] == 'Owner':
                owner = tags["Value"]
    else:
        instancename='-'
    print("Inastance Name - %s,  Instance Id - %s, Owner - %s " %(instancename,instance.id,owner))
   
Share:
25,997
Narasimha Theja Rao
Author by

Narasimha Theja Rao

Updated on October 07, 2021

Comments

  • Narasimha Theja Rao
    Narasimha Theja Rao over 2 years

    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': '[email protected]'}])
    print(response)
    
  • Narasimha Theja Rao
    Narasimha Theja Rao over 6 years
    Thank You!! with few modification i can able to achieve my requirement!