AWS - Using Python and Boto3 to get Information about Untagged EC2 resources

Just a quick post on a Python script to scan through all your EC2 Instances in the Specified Region, and if there's no Tags associated to the resource, the script will print information out about the resources in question.

Below is the Python Script:

import boto3

session = boto3.Session(

ec2 = session.client('ec2')

response = ec2.describe_instances()

obj_number = len(response['Reservations'])

for objects in xrange(obj_number):
        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']
        untagged_keyname = response['Reservations'][objects]['Instances'][0]['KeyName']
        print("InstanceID: {0}, RunningState: {1}, KeyName: {2}".format(untagged_instanceid, untagged_state, untagged_keyname))

Running the python script, will result in a format like below:

$ python get_untagged_ec2.py
InstanceID: i-012345abcde, RunningState: running, KeyName: mykey
InstanceID: i-012345fghij, RunningState: running, KeyName: mykey
InstanceID: i-012345klmno, RunningState: running, KeyName: mykey