Last active
February 12, 2019 01:29
-
-
Save ruanbekker/bfd689c3bd55357770a7805c2ef17569 to your computer and use it in GitHub Desktop.
AWS EC2: Get All Untagged EC2 Instances
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment