Search code examples
jqaws-cliamazon-cloudtrail

Extract key values from CloudTrail Lookup-Events from AWS-CLI using jq


i ran the command to get the lookup-events for ConsoleLogin activities in AWS Account.I want to extract the key values for mfaAuthenticated , eventSource and eventType from this given json output

The output i got from the above command

{
  "eventVersion": "1.08",
  "userIdentity": {
    "type": "AssumedRole",
    "principalId": "XXXXXXXXXXXXXXXXX:dkboss",
    "arn": "XXXXXXXXXXXXXXXXXXXXXXXXX/dkboss",
    "accountId": "XXXXXXXXXXXXXXXX",
    "sessionContext": {
      "sessionIssuer": {
        "type": "Role",
        "principalId": "XXXXXXXXXXXXXXXXXXXXXXXXXX",
        "arn": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
        "accountId": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
        "userName": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
      },
      "webIdFederationData": {},
      "attributes": {
        "creationDate": "2022-11-27T15:24:28Z",
        "mfaAuthenticated": "false"             ---------> i want this key value
      }
    }
  },
  "eventTime": "2022-11-27T15:24:29Z",
  "eventSource": "signin.amazonaws.com", ---------> i want this key value
  "eventName": "ConsoleLogin",
  "awsRegion": "us-east-1",
  "sourceIPAddress": "1.1.1.1",
  "userAgent": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "requestParameters": null,
  "responseElements": {
    "ConsoleLogin": "Success"
  },
  "additionalEventData": {
    "MobileVersion": "No",
    "MFAUsed": "No"
  },
  "eventID": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "readOnly": false,
  "eventType": "AwsConsoleSignIn",      ---------> i want this key value
  "managementEvent": true,
  "recipientAccountId": "XXXXXXXXXXXXXXXXXXXXXXX",
  "eventCategory": "Management",
  "tlsDetails": {
    "tlsVersion": "TLSv1.2",
    "cipherSuite": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    "clientProvidedHostHeader": "signin.aws.amazon.com"
  }
}

I ran this command to get the above json output :

aws cloudtrail --region us-east-1 lookup-events --lookup-attributes AttributeKey=EventName,AttributeValue=ConsoleLogin --start-time $(date -d "-60 minutes" +%s) --query 'Events[].CloudTrailEvent.attributes' --output text | jq


Solution

  • You didn't give any conditions how to select the nodes, or how to format your output. So, how about just traversing to their locations. With the --raw-output (or -r) option, jq will output their decoded values. Making it a stream in the filter (by separating them with commas ,) will make it a newline-separated list in the output.

    jq --raw-output '
      .userIdentity.sessionContext.attributes.mfaAuthenticated,
      .eventSource,
      .eventType
    '
    
    false
    signin.amazonaws.com
    AwsConsoleSignIn