How can I create a custom event pattern for an EventBridge rule?

5 minute read
0

I want to capture certain events for AWS services with an Amazon EventBridge rule. However, I'm unable to create a custom event pattern that matches the event. How can I create a custom EventBridge event pattern?

Resolution

Note: If you receive errors when running AWS Command Line Interface (AWS CLI) commands, make sure that you're using the most recent AWS CLI version.

EventBridge accepts events from AWS Services, EventBridge Partners, and custom events. This article discusses JSON events originating from AWS services. You can create EventBridge rules with event patterns to filter incoming events. This way, the EventBridge rule matches only the desired events and forwards those events to the targets.

Determine the JSON format of the incoming event

There are three methods for determining the JSON format for an incoming event:

  1. Open the EventBridge console.
  2. From the navigation pane, under Developer resources, select Sandbox.
  3. Scroll to the Sample event section, then select AWS events.
  4. From the Sample events menu, select EC2 Instance State-change Notification. This populates the window with the first sample event. For a given event type, multiple samples might be available.
  • Create an EventBridge rule with a simple event pattern that matches all events for a given AWS service. For example, this event pattern matches all Amazon Elastic Compute Cloud (Amazon EC2) events:
{
 "source": [ "aws.ec2" ]
}

Note: Wildcards and empty events aren't allowed in the event pattern.

Next, associate an SNS or a CloudWatch Log Group target with the rule to capture inbound events. The target must have the Configure target input option set to Matched events so the JSON emitted by the service is received correctly.

Create an event pattern in the same JSON format as the incoming event

The following rules apply to creating a valid matching event pattern:

  • Any fields that you don't specify in your event pattern are automatically matched. For example, if Detail isn't specified in the event pattern, then the event pattern matches every event with any detail.
  • To match fields that are one level down in the JSON structure, use curly brackets { }. A JSON viewer might be helpful if you're looking at larger event structures.
  • The string to be matched from the JSON event must be in square brackets [ ]. You can include multiple values in square brackets so that the event is invoked when either of the values are present in an incoming event. For example, to invoke an event based on every event sent by Amazon EC2 or Amazon DynamoDB, use this filter:
{
 "source": [ "aws.ec2", "aws.dynamodb" ]
}

Step 1: Obtain incoming event using SNS / CloudWatch target

This example shows a Route 53 event emitted to EventBridge. The ChangeResourceRecordSets API call represents the creation of an A record in an Amazon Route 53 hosted zone. An Amazon Simple Notification Service (Amazon SNS) topic or Amazon CloudWatch Log Group target captures the following event:

{
  "version": "0",
  "id": "d857ae5c-cc83-3742-ab88-d825311ee4e9",
  "detail-type": "AWS API Call via CloudTrail",
  "source": "aws.route53",
  "account": "123456789012",
  "time": "2019-12-05T16:50:53Z",
  "region": "us-east-1",
  "resources": [],
  "detail": {
    "eventVersion": "1.05",
    "userIdentity": {
      "type": "AssumedRole",
      "principalId": "AROAABCDEFGHIJKLMNOPQ:Admin",
      "arn": "arn:aws:sts::123456789012:assumed-role/Admin",
      "accountId": "123456789012",
      "accessKeyId": "ASIAABCDEFGH12345678",
      "sessionContext": {
        "sessionIssuer": {
          "type": "Role",
          "principalId": "AROAABCDEFGHIJKLMNOPQ",
          "arn": "arn:aws:iam::123456789012:role/Admin",
          "accountId": "123456789012",
          "userName": "Admin"
        },
        "webIdFederationData": {},
        "attributes": {
          "mfaAuthenticated": "false",
          "creationDate": "2019-12-05T16:28:27Z"
        }
      }
    },
    "eventTime": "2019-12-05T16:50:53Z",
    "eventSource": "route53.amazonaws.com",
    "eventName": "ChangeResourceRecordSets",
    "awsRegion": "us-east-1",
    "sourceIPAddress": "12.34.56.78",
    "userAgent": "console.amazonaws.com",
    "requestParameters": {
      "hostedZoneId": "Z1RP12345WXRQD",
      "changeBatch": {
        "changes": [
          {
            "action": "CREATE",
            "resourceRecordSet": {
              "type": "A",
              "tTL": 300,
              "resourceRecords": [
                {
                  "value": "4.4.4.4"
                }
              ],
              "name": "test.example.us."
            }
          }
        ]
      }
    },
    "responseElements": {
      "changeInfo": {
        "status": "PENDING",
        "id": "/change/C271P4WIKN511J",
        "submittedAt": "Dec 5, 2019 4:50:53 PM"
      }
    },
    "additionalEventData": {
      "Note": "Do not use to reconstruct hosted zone"
    },
    "requestID": "bbbf9847-96cb-45ef-b617-d535b9fe83d8",
    "eventID": "74e2d2c8-7497-4292-94d0-348272dbc4f7",
    "eventType": "AwsApiCall",
    "apiVersion": "2013-04-01"
  }
}

Step 2: Create the corresponding EventPattern

This example event pattern filters on a number of fields. For example, eventName, hostedZoneld, action, and type. Matching events must contain all the fields and corresponding values. The pattern isolates the A records created against a specific hosted zone.

{
  "source": [
    "aws.route53"
  ],
  "detail": {
    "eventSource": [
      "route53.amazonaws.com"
    ],
    "eventName": [
      "ChangeResourceRecordSets"
    ],
    "requestParameters": {
      "hostedZoneId": [
        "Z1RP12345WXRQD"
      ],
      "changeBatch": {
        "changes": {
          "action": [
            "CREATE"
          ],
          "resourceRecordSet": {
            "type": [
              "A"
            ]
          }
        }
      }
    }
  }
}

Test the event pattern

Test using the EventBridge console

Leverage the EventBridge Sandbox: 

  1. From the Sample event section, select or enter a sample event.
  2. Under Event pattern section, provide an event pattern. You can do this either by building an event pattern using the menus in the Event pattern form or by entering a custom event pattern with the Custom patterns (JSON editor).
  3. After both sections are populated, select Test pattern to confirm that the event pattern matches the given sample event.

Test using the AWS CLI

In the AWS CLI, run the test-event-pattern command. To confirm that the event pattern matches, be sure that the result is true. By doing this, you can identify the JSON events sent by the AWS service and help your custom event pattern to capture specific events.


Related information

Amazon EventBridge event patterns

Creating Amazon EventBridge rules that react to events

Tutorial: Log AWS API calls using EventBridge

Amazon EventBridge - What's the difference between CloudWatch Events and EventBridge? (video)

AWS OFFICIAL
AWS OFFICIALUpdated a year ago