Skip to content

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

5 minute read
0

I want to use an Amazon EventBridge rule to capture events for AWS services. However, I can't create a custom event pattern that matches the event.

Resolution

Note: If you receive errors when you run AWS Command Line Interface (AWS CLI) commands, then see Troubleshooting errors for the AWS CLI. Also, make sure that you're using the most recent AWS CLI version.

Create an event pattern and EventBridge rule

The following procedure uses the EventBridge Sandbox to create and test an EC2 Instance State-change event.

Complete the following steps:

  1. Open the EventBridge console.
  2. In the navigation pane, choose Developer resources, and then choose Sandbox.
  3. On the Event pattern tab, in the Sample event section, choose AWS events.
  4. In the Sample events field, choose EC2 Instance State-change Notification.
    Note: Depending on the event type, multiple samples might be available.
  5. In the Creation method section, test the event pattern.

Create an EventBridge rule with an event pattern that matches all events for an AWS service. For example, the following event pattern matches all Amazon Elastic Compute Cloud (Amazon EC2) events:

{ 
  "source": [ "aws.ec2" ]
}

Note: The event pattern can't contain empty events. All events that you specify in the pattern must include valid content or criteria.

To capture inbound events, associate an Amazon Simple Notification Service (Amazon SNS) topic or an Amazon CloudWatch log group target with the rule. For the target, set the Configure target input option to Matched events so that EventBridge receives the JSON that the service sends.

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

To create an event pattern in the same JSON format as the incoming event, you must match the event's structure and fields.

An event pattern match is inclusive by default. A field that you remove from your event pattern acts as a wildcard and matches all possible values for the field. For example, if you don't include the Detail field in your pattern, then the system matches events regardless of the Detail content.

To match fields that are one level down in the JSON structure, use curly brackets. For larger event structures, use a JSON viewer.

When you specify values to match in your event pattern, enclose them in square brackets. You can define multiple acceptable values, and create an OR condition. If one of the values is in an incoming event, then the rule activates. For example, to create a rule that activates for events from either Amazon EC2 or Amazon DynamoDB, use the following pattern:

{
  "source": ["aws.ec2", "aws.dynamodb"]
}

Use Amazon SNS topic or a CloudWatch log group to get the incoming event

In the following example, Amazon Route 53 sends an event to EventBridge through AWS CloudTrail. The ChangeResourceRecordSets API call creates an A record in a Route 53 hosted zone. An Amazon SNS topic or CloudWatch log group target captures the 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"
  }
}

Create the corresponding event pattern

The following event pattern is an example of multi-field filtering. For an event to match the pattern, the event must include all the specified fields with their corresponding values. The following pattern identifies only A type record creations within a designated 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

To test the event pattern, use either the EventBridge console or the AWS CLI.

EventBridge console

Use the Sandbox on the EventBridge console. For Event pattern, choose Enter my own.

AWS CLI

Run the following test-event-pattern command:

aws events test-event-pattern --event-pattern "{\"source\":[\"com.mycompany.myapp\"]}" --event "{\"id\":\"1\",\"source\":\"com.mycompany.myapp\",\"detail-type\":\"myDetailType\",\"account\":\"123456789012\",\"region\":\"us-east-1\",\"time\":\"2017-04-11T20:11:04Z\"}"

A true result confirms that your event pattern matches the event.

Related information

Amazon EventBridge event patterns

Tutorial: Create an EventBridge rule that reacts to AWS API calls via CloudTrail

Amazon EventBridge - What's the difference between CloudWatch events and EventBridge? on the YouTube channel for Serverless Land