Who created an Amazon EC2 instance using Boto and

2019-04-17 15:58发布

问题:

I want to know who created a particular instance. I am using Cloud Trail to find out the statistics, but I am not able to get a particular statistics of who created that instance. I am using Python and Boto3 for finding out the details. I am using this code- Lookup events() from Cloud trail in boto3, to extract the information about an instance.

ct_conn = sess.client(service_name='cloudtrail',region_name='us-east-1')


events=ct_conn.lookup_events()

回答1:

I found out the solution to the above problem using lookup_events() function.

ct_conn = boto3.client(service_name='cloudtrail',region_name='us-east-1')

events_dict= ct_conn.lookup_events(LookupAttributes=[{'AttributeKey':'ResourceName', 'AttributeValue':'i-xxxxxx'}])
for data in events_dict['Events']:
    json_file= json.loads(data['CloudTrailEvent'])
    print json_file['userIdentity']['userName']


回答2:

@Karthik - Here is the sample of creating session

import boto3
import json
import os

session = boto3.Session(region_name='us-east-1',aws_access_key_id=os.environ['AWS_ACCESS_KEY_ID'],aws_secret_access_key=os.environ['AWS_SECRET_ACCESS_KEY'])

ct_conn = session.client(service_name='cloudtrail',region_name='us-east-1')

events_dict= ct_conn.lookup_events(LookupAttributes=[{'AttributeKey':'ResourceName', 'AttributeValue':'i-xxx'}])

for data in events_dict['Events']:
    json_file= json.loads(data['CloudTrailEvent'])
    print (json_file['userIdentity']['userName'])