Explore Courses Blog Tutorials Interview Questions
0 votes
in AWS by (19.1k points)

I'm trying to get the following:

Get all EC2 instances that either:

  1. are Tagged with tag Owner and value Unknown or unknown
  2. are missing tag Owner

I'm able to accomplish 1) but no idea how to get 2)

import boto3   

import collections     

import datetime     

import time     

import sys 

ec = boto3.client('ec2', 'eu-west-1')     

ec2 = boto3.resource('ec2', 'eu-west-1')     

def lambda_handler(event, context):           

    instance_ids = []

    reservations = ec.describe_instances(     


            {'Name': 'tag:Owner', 'Values': ['Unknown', 'unknown']},     


    ).get('Reservations', []) 

    for reservation in reservations:

          instances = reservation['Instances']

          for instance in instances:


    print("Stopping instances: {}".format(','.join(instance_ids)))

1 Answer

0 votes
by (44.4k points)

Owner filter so your response includes instances without Owner tag as well, and then you get to filtering locally.

reservations = ec.describe_instances().get('Reservations', [])

for reservation in reservations:

    for instance in reservation['Instances']:

        tags = {}

        for tag in instance['Tags']:

            tags[tag['Key']] = tag['Value']

        if not 'Owner' in tags:

            print instance['InstanceId'] + " does not have Owner tag"

        elif tags['Owner'] in ['Unknown', 'unknown']:

            print instance['InstanceId'] + " has [U|u]nknown Owner tag"

If you have a large number of instances in your account, the response to describe_instances may be paginated, and you'll have to deal with that as well.

Related questions

Want to get 50% Hike on your Salary?

Learn how we helped 50,000+ professionals like you !

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories