ruanbekker
7/26/2017 - 3:40 PM

AWS EC2: Get All Untagged EC2 Instances

AWS EC2: Get All Untagged EC2 Instances

import boto3

# setting region, profile from credential provider
session = boto3.Session(
        region_name='eu-west-1',
        profile_name='myprofile'
        )

# declare ec2
ec2 = session.client('ec2')

# get a dictionary of all the instances
response = ec2.describe_instances()

# get the number of objects
obj_number = len(response['Reservations'])

# print the instance-id's with no tags
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']
        untagged_keyname = response['Reservations'][objects]['Instances'][0]['KeyName']
        print("InstanceID: {0}, RunningState: {1}, KeyName: {2}".format(untagged_instanceid, untagged_state, untagged_keyname))

# $ python get_untagged_ec2.py
# InstanceID: i-03b7608f2a9784cef, RunningState: running, KeyName: mykey
# InstanceID: i-01383968e138c20a4, RunningState: running, KeyName: mykey
# InstanceID: i-07ad00e454439f0c0, RunningState: running, KeyName: mykey