Created
February 16, 2018 16:47
-
-
Save sudharsans/39d5eaf8a82b7ccdf8b3230d13ba7d81 to your computer and use it in GitHub Desktop.
list of all EC2 instances created by IAM user
This file contains 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 | |
ec2 = boto3.client('ec2') | |
cloudtrail = boto3.client('cloudtrail') | |
def get_user(instanceid): | |
response = cloudtrail.lookup_events ( | |
LookupAttributes=[ | |
{ | |
'AttributeKey': 'ResourceName', | |
'AttributeValue': instanceid | |
} | |
], | |
) | |
return response | |
def get_ec2_owner(instanceid): | |
user_details = get_user (instanceid) | |
for event in user_details.get ("Events"): | |
if event.get ("EventName") == "RunInstances": | |
return event.get ("Username") | |
response = ec2.describe_instances (Filters=[ | |
{ | |
'Name': 'instance-state-name', | |
'Values': ['running'] | |
} | |
]) | |
for r in response['Reservations']: | |
for instance in r['Instances']: | |
user = get_ec2_owner (instance['InstanceId']) | |
print (instance['InstanceId'],user) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment