Skip to content

Instantly share code, notes, and snippets.

@sudharsans
Created February 16, 2018 16:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save sudharsans/39d5eaf8a82b7ccdf8b3230d13ba7d81 to your computer and use it in GitHub Desktop.
Save sudharsans/39d5eaf8a82b7ccdf8b3230d13ba7d81 to your computer and use it in GitHub Desktop.
list of all EC2 instances created by IAM user
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