Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find instances that DONT have a tag using Boto3

I'm trying to find instances that DONT have a certain tag.

For instance I want all instances that don't have the Foo tag. I also want instances that don't have the Foo value equal to Bar.

This is what I'm doing now:

import boto3


def aws_get_instances_by_name(name):
    """Get EC2 instances by name"""
    ec2 = boto3.resource('ec2')

    instance_iterator = ec2.instances.filter(
        Filters=[
            {
                'Name': 'tag:Name',
                'Values': [
                    name,
                ]
            },
            {
                'Name': 'tag:Foo',
                'Values': [

                ]
            },
        ]
    )

    return instance_iterator

This is returning nothing.

What is the correct way?

like image 859
Ayush Sharma Avatar asked Oct 14 '16 10:10

Ayush Sharma


People also ask

What are instance tags?

Tags enable you to categorize your AWS resources in different ways, for example, by purpose, owner, or environment. For example, you could define a set of tags for your account's Amazon EC2 instances that helps you track each instance's owner and stack level.

How do I delete a Boto3 instance?

You can do this very easily using the boto3 library. all you need is to create a list of ids of all the ec2 instances you wish to terminate. Then using the filter method pass in that list of ids as a keyworded argument named InstanceIds and call the terminate method on the returned value and you are done.


1 Answers

Here's some code that will display the instance_id for instances without a particular tag:

import boto3

instances = [i for i in boto3.resource('ec2', region_name='ap-southeast-2').instances.all()]

# Print instance_id of instances that do not have a Tag of Key='Foo'
for i in instances:
  if i.tags is not None and 'Foo' not in [t['Key'] for t in i.tags]:
    print i.instance_id
like image 116
John Rotenstein Avatar answered Oct 09 '22 23:10

John Rotenstein