I'm working on a lambda function that gets events from CloudTrail and analyse them.
I have this script:
s3.download_file(bucket, key, download_path)
with gzip.open(download_path, "r") as f:
data = json.loads(f.read())
print json.dumps(data)
for event in data['Records']:
if event['eventName'] in event_list:
dateEvent = datetime.strptime(event['eventTime'], "%Y-%m-%dT%H:%M:%SZ")
for element in event['userIdentity']:
for session in element[0]['sessionContext']:
username = session['userName']
role = session['arn']
I can't get out of the event the value of userName
and the arn
. I get this error:
string indices must be integers: TypeError
Traceback (most recent call last):
File "/var/task/lambda_function.py", line 34, in lambda_handler
for session in element[0]['sessionContext']:
TypeError: string indices must be integers
How to make that work? What is the right way?
Here is the json string:
"userIdentity": {
"principalId": "aaaaaaaaaaaaaaaaaaaa",
"accessKeyId": "aaaaaaaaaaaaaaaaaaaaa",
"sessionContext": {
"sessionIssuer": {
"userName": "aaaaaaaaaaaaa",
"type": "Role",
"arn": "arn:aws:iam::aaaaaaaaaaaaaaaaaa:role/aaaaaaa",
"principalId": "aaaaaaaaaaaaaaaaaa",
"accountId": "aaaaaaaaaaaaaaaaaaa"
},
"attributes": {
"creationDate": "2017-09-14T15:03:08Z",
"mfaAuthenticated": "false"
}
},
"type": "AssumedRole",
"arn": "aaaaaaaaaaaaaaaaaaaaaaaa",
"accountId": "aaaaaaaaaaaaaaaaaa"
},
The
userIdentity
element may or may not have asessionContext
element because those only exist if temporary IAM credentials were used during that event.A
userIdentity
element withoutsessionContext
looks like this:But a
userIdentity
with asessionContext
element would look like like this:...or it could even look like this if no role federation occurred.
So going back to your code:
element[0]
doesn't exist becausesessionContext
isn't a list.If you want to fetch the used or assumed username and role ARN, I think this would work. It takes into account events that were done directly via
IAMUser
or viaAssumedRole
.And as a part of your processing loop: