Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 817
Narasimha Theja Rao Avatar asked Jan 03 '18 06:01

Narasimha Theja Rao


3 Answers

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)
like image 127
helloV Avatar answered Oct 12 '22 16:10

helloV


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))
   
like image 1
T_Square Avatar answered Oct 12 '22 14:10

T_Square


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()
like image 1
Sheikh Aafaq Rashid Avatar answered Oct 12 '22 14:10

Sheikh Aafaq Rashid