Ahsan Naseem
Ahsan Naseem

Reputation: 1106

How to get not tagged instance in AWS in Boto3?

I want to get instances which are not tagged by some specific key but unable to get desired output below is my code

import boto3
import json
import time
import os

client = boto3.client('ec2')
response = client.describe_instances(
#    DryRun=True|False,
    Filters=[
        {
            'Name': 'tag: elasticbeanstalk:environment-name',
            'Values': [
                'Not tagged'
            ]
        }
    ]
)
print(response)

output I am getting

{u'Reservations': [], 'ResponseMetadata': {'RetryAttempts': 0, 'HTTPStatusCode': 200, 'RequestId': 'b66a2bb5-ac75-4bc1-b359-fdac50fdfaee', 'HTTPHeaders': {'transfer-encoding': 'chunked', 'vary': 'Accept-Encoding', 'server': 'AmazonEC2', 'content-type': 'text/xml;charset=UTF-8', 'date': 'Tue, 21 Mar 2017 12:55:12 GMT'}}}

reference: boto3 reference

Upvotes: 1

Views: 2730

Answers (2)

Ruan B.
Ruan B.

Reputation: 521

I've used the following before to get InstanceIds of EC2 which is not tagged, you could modify the code a bit to get the desired output.

Hope it helps:

import boto3

session = boto3.Session(
        region_name='eu-west-1',
        profile_name='myprofile'
        )

ec2 = session.client('ec2')

response = ec2.describe_instances()

obj_number = len(response['Reservations'])

for objects in xrange(obj_number):
    try:
        z = response['Reservations'][objects]['Instances'][0]['Tags'][0]['Key']
    except KeyError as e:
        untagged_instanceid = response['Reservations'][objects]['Instances'][0]['InstanceId']
        untagged_state = response['Reservations'][objects]['Instances'][0]['State']['Name']
        print("InstanceID: {0}, RunningState: {1}".format(untagged_instanceid, untagged_state))

The output for the above code, will look like the following:

$ python get_untagged_ec2.py
InstanceID: i-012345abcdefg, RunningState: running
InstanceID: i-123456hijklmn, RunningState: running
InstanceID: i-234567opqrstu, RunningState: running

Upvotes: 0

talentedmrjones
talentedmrjones

Reputation: 8161

From what I can tell the underlying API does not support this kind of filtering. The only way to find it would be to query for everything, or a subset of machines in a particular state such as RUNNING, then do the filtering for untagged resources in python.

See this related question: Finding all Amazon AWS Instances That Do Not Have a Certain Tag

Upvotes: 1

Related Questions