0

Sometimes (not often) JSON below has additional field between EventName and EventSources called Username.

For example:

"EventName": "AssumeRole",
"EventSource": "sts.amazonaws.com",
"Username": "someuser"

and sometimes it doesn't (as below)

I want to create if else, so if "Username": "someuser" is there, print one output, if not, print another.

with open('1.json') as file:
 data = json.load(file)

with open('cloudtrail.csv', 'wt') as file:
 #file.write('ResourceType,ResourceName,EventName,UserName\n')
 for element in data['Events']:
  if element['Username']:
   for resource in element['Resources']:
    print(resource['ResourceType'] + ',' + resource['ResourceName'] + ',' + element['EventName'] + ',' + element['Username'])
  else:
    print(resource['ResourceType'] + ',' + resource['ResourceName'] + ',' + element['EventName'])

But facing this (because element['Username'] doesn't exist):

File "./cloud.py", line 24, in <module>
    if element['Username']:
KeyError: 'Username'

Obviously, something is wrong in my if else logic

{
    "Events": [
        {
            "EventId": "62c8bac9-c486-4e1e-9603-58d8ba4a20f4",
            "EventTime": 1529020719.0,
            "CloudTrailEvent": "{\"eventVersion\":\"1.05\",\"userIdentity\":{\"type\":\"AWSService\",\"invokedBy\":\"vpc-flow-logs.amazonaws.com\"},\"eventTime\":\"2018-06-14T23:58:39Z\",\"eventSource\":\"sts.amazonaws.com\",\"eventName\":\"AssumeRole\",\"awsRegion\":\"us-east-1\",\"sourceIPAddress\":\"vpc-flow-logs.amazonaws.com\",\"userAgent\":\"vpc-flow-logs.amazonaws.com\",\"requestParameters\":{\"roleArn\":\"arn:aws:iam::279052847476:role/flowlogsRole\",\"roleSessionName\":\"vpc-flow-logging+279052847476\",\"externalId\":\"vpc-flow-logging+279052847476\",\"durationSeconds\":3600},\"responseElements\":{\"credentials\":{\"accessKeyId\":\"ASIAIOD3JIGRTBSRNP7A\",\"expiration\":\"Jun 15, 2018 12:58:39 AM\",\"sessionToken\":\"FQoDYXdzEIH//////////wEaDHKlf7uMLL744fS/RCLgAcSDdZYK7gVctXe76EuIIC+De68ZK21fz30fWwGuxRFmiMREIjLMZmxD/vMsNKLVoutHOLJzBs1VIi62uf8reZThmuU2eFQI1DVAM9Pmfr7iWySEX0ZzmaD9kuNPTM0T1OqudTqopDtgU0aRL0t6jlhASOK6UvH/2eNllSaFxU0l51GaUDfrKqRR9ejqAs0PyQx/0ymq71yqCRT2dVuyACVF9nbs0agt/y4Ke3T5MpKrjQUhPQF4c77sxGN3/OuMkx7G91pBYifjuOMx1SWf7PuqoU0hIEPmzmfmJdVMRbKpKK+CjNkF\"},\"assumedRoleUser\":{\"assumedRoleId\":\"AROAJMTKGPJI67TAWGXVG:vpc-flow-logging+279052847476\",\"arn\":\"arn:aws:sts::279052847476:assumed-role/flowlogsRole/vpc-flow-logging+279052847476\"}},\"requestID\":\"dc1636da-702e-11e8-a991-13cc235e6bd3\",\"eventID\":\"62c8bac9-c486-4e1e-9603-58d8ba4a20f4\",\"resources\":[{\"ARN\":\"arn:aws:iam::279052847476:role/flowlogsRole\",\"accountId\":\"279052847476\",\"type\":\"AWS::IAM::Role\"}],\"eventType\":\"AwsApiCall\",\"recipientAccountId\":\"279052847476\",\"sharedEventID\":\"c06bf41d-9758-4b33-abdb-86774f67c5c9\"}",
            "EventName": "AssumeRole",
            "EventSource": "sts.amazonaws.com",
            "Resources": [
                {
                    "ResourceType": "AWS::IAM::AccessKey",
                    "ResourceName": "ASIAIOD3JIGRTBSRNP7A"
                },
                {
                    "ResourceType": "AWS::STS::AssumedRole",
                    "ResourceName": "vpc-flow-logging+279052847476"
                },
                {
                    "ResourceType": "AWS::STS::AssumedRole",
                    "ResourceName": "arn:aws:sts::279052847476:assumed-role/flowlogsRole/vpc-flow-logging+279052847476"
                },
                {
                    "ResourceType": "AWS::STS::AssumedRole",
                    "ResourceName": "AROAJMTKGPJI67TAWGXVG:vpc-flow-logging+279052847476"
                },
}]
melpomene
  • 84,125
  • 8
  • 85
  • 148
Milister
  • 648
  • 1
  • 15
  • 33

2 Answers2

4

Try this condition:

if 'Username' in element:
fafl
  • 7,222
  • 3
  • 27
  • 50
  • IMHO this is the cleaner solution, but some people would suggest that in python is [easier to ask forgiveness than permission](https://stackoverflow.com/questions/12265451/ask-forgiveness-not-permission-explain) – leoschet Jun 15 '18 at 10:32
0

Use try-except statements

try:
    username = element['Username']
except KeyError:
    # Deal with it
    username = None

# note that the try statement does not create a new scope
if username is not None:
    print(username)

You can easily reuse this structure for the other keys.

For completeness, I should note that one can also use else and finally together with the try-except. The else statement will only be executed if except wasn't. The finally will run no matter what happened.

leoschet
  • 1,697
  • 17
  • 33