Narasimha Theja Rao
Narasimha Theja Rao

Reputation: 199

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': '[email protected]'}])
print(response)

Upvotes: 15

Views: 46244

Answers (7)

TanoDevOps
TanoDevOps

Reputation: 11

Use "resource" to get a list of the instances

import boto3
ec2 = boto3.resource('ec2', "ap-southeast-2")
instances = ec2.instances.filter(
Filters=[
    {
        'Name': 'instance-state-name',
         'Values': [
            'running'
            ]
    },
    {
        'Name': 'tag:BusinessService',
        'Values': [
            '<insert tag>'
        ]
    },
]

)

Or use "client" to get a Dict

import boto3
ec2_cli = boto3.client('ec2', region_name='ap-southeast-2')
instances = ec2_cli.describe_instances(
Filters=[
    {
        'Name': 'instance-state-name',
         'Values': [
            'running'
            ]
    },
    {
        'Name': 'tag:BusinessService',
        'Values': [
            '<insert tag>'
        ]
    },
]
)

Upvotes: 1

furydrive
furydrive

Reputation: 510

    ec2_client = boto3.client('ec2')
        
    response = ec2_client.describe_tags(
        DryRun=False,
        Filters = [
            {
                'Name': 'resource-id',
                'Values': [
                    instance_ID,
                    ],
            },
            {
                'Name': 'key',
                'Values': ['key_of_the_tag_you_want_to_fetch']
                
            },
        ],
    )

tag_value = response['Tags'][0]['Value']

The variable tag_value will hold the value of tag with key ['key_of_the_tag_you_want_to_fetch']. instance_ID is the Id of the instance you want to fetch the tag values from.

Upvotes: 0

Sheikh Aafaq Rashid
Sheikh Aafaq Rashid

Reputation: 199

Stop instances that are running and have no tags

    import boto3
    ec2 = boto3.resource('ec2',"ap-south-1")
    instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])
    for instance in instances:
        #print(instance.tags)
        if instance.tags == None:
            print(instance.id)
            instance.stop()
        else:
            pass

stop all running instances with a specific tag like tag key ='env'

import boto3
ec2 = boto3.resource('ec2',"ap-south-1")

# filter all running instances
instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])

# Decleared list to store running instances
all_running_instances = []
specific_tag = 'env'  
for instance in instances:
    
    # store all running instances
     all_running_instances.append(instance)
        
    # Instances with specific tags
     if instance.tags != None:
         for tags in instance.tags:
             
            # Instances with tag 'env'
             if tags["Key"] == specific_tag:
                
                # Remove instances with specefic tags from all running instances
                 all_running_instances.remove(instance)
                    
#print(all_running_instances)
for specific in all_running_instances:
    print(specific)
    specific.stop()

Upvotes: 1

Sheikh Aafaq Rashid
Sheikh Aafaq Rashid

Reputation: 199

List instances that are running and have no tags

import boto3
ec2 = boto3.resource('ec2',"ap-south-1")
instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])
for instance in instances:
    #print(instance.tags)
    if instance.tags == None:
        print(instance.id)
        instance.stop()
    else:
        pass

Upvotes: 0

T_Square
T_Square

Reputation: 23

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))
   

Upvotes: 1

helloV
helloV

Reputation: 52453

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)

Upvotes: 43

mootmoot
mootmoot

Reputation: 13176

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' : ['[email protected]']}
]
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.

Upvotes: -3

Related Questions