

# Creating Amazon EventBridge event patterns
<a name="eb-event-patterns"></a>

Chances are you won't want to process every single event that gets delivered to a given event bus or pipe. Rather, you'll likely want to select a subset of all the events delivered, based on the source of the event, the event type, and/or attributes of those events. 

To specify which events to send to a target, you create an *event pattern*. An event pattern defines the data EventBridge uses to determine whether to send the event to the target. If the event pattern matches the event, EventBridge sends the event to the target. Event patterns have the same structure as the events they match. An event pattern either matches an event or it doesn't.

**Tip**  
You can use the EventBridge Sandbox to test event patterns against sample events before creating or updating rules. For more information, see [Testing event patterns using the EventBridge Sandbox](eb-event-pattern-sandbox.md).

For example, consider the following event from Amazon EC2:

```
{
  "version": "0",
  "id": "6a7e8feb-b491-4cf7-a9f1-bf3703467718",
  "detail-type": "EC2 Instance State-change Notification",
  "source": "aws.ec2",
  "account": "111122223333",
  "time": "2017-12-22T18:43:48Z",
  "region": "us-west-1",
  "resources": [
    "arn:aws:ec2:us-west-1:123456789012:instance/i-1234567890abcdef0"
  ],
  "detail": {
    "instance-id": "i-1234567890abcdef0",
    "state": "terminated"
  }
}
```

The following event pattern selects all Amazon EC2 `instance-termination` events. The event pattern does this by specifying three requirements to match an event:

1. The event source must be Amazon EC2.

1. The event must be an Amazon EC2 state-change notification.

1. The state of the Amazon EC2 instance must be `terminated`.

```
{
  "source": ["aws.ec2"],
  "detail-type": ["EC2 Instance State-change Notification"],
  "detail": {
    "state": ["terminated"]
  }
}
```

Note that in this example, the event pattern includes fields *about* the event--`source` and `detail-type`--as well as a field from the event body--`state`.

**Important**  
In EventBridge, it is possible to create rules that can lead to higher-than-expected charges and throttling. For example, you can inadvertently create a rule that leads to an infinite loop, where a rule is fired recursively without end. Suppose you created a rule to detect that ACLs have changed on an Amazon S3 bucket, and trigger software to change them to the desired state. If the rule is not written carefully, the subsequent change to the ACLs fires the rule again, creating an infinite loop.  
For guidance on how to write precise rules and event patterns to minimize such unexpected results, see [Best practices for rules](eb-rules-best-practices.md) and [Best practices](eb-patterns-best-practices.md).

## Event patterns for event buses
<a name="eb-event-patterns-buses"></a>

For event buses, you can specify an event pattern for each rule you create for the bus. In this way, you can select which events to send to specific targets. Event patterns for event buses can match against the event source, event metadata, and/or event detail values.

![\[An event is compared to each bus rule's event pattern, and sent to the target if it matches.\]](http://docs.aws.amazon.com/eventbridge/latest/userguide/images/event-pattern-bus_eventbridge_architecture.svg)


 The following video discusses the basics of event patterns for event buses:




## Event patterns for EventBridge Pipes
<a name="eb-event-patterns-pipes"></a>

For EventBridge Pipes, you can specify event patterns to filter the events from the pipe source that you want delivered to the pipe target. Since each pipe has a single event source, event patterns for pipes can match against event metadata and/or detail values.

![\[An event is compared against the pipe's event pattern, and sent to the target if it matches.\]](http://docs.aws.amazon.com/eventbridge/latest/userguide/images/event-pattern-pipes_eventbridge_architecture.svg)


Not all event fields can be used to construct pipe event patterns. For more information, see [Filtering](eb-pipes-event-filtering.md).

# Event pattern syntax
<a name="eb-create-pattern"></a>

To create an event pattern, you specify the fields of an event that you want the event pattern to match. Only specify the fields that you use for matching. 

For example, the following event pattern example only provides values for three fields: the top-level fields `"source"` and `"detail-type"`, and the `"state"` field inside the `"detail"` object field. EventBridge ignores all the other fields in the event when applying the rule.

```
{
  "source": ["aws.ec2"],
  "detail-type": ["EC2 Instance State-change Notification"],
  "detail": {
    "state": ["terminated"]
  }
}
```

For an event pattern to match an event, the event must contain all the field names listed in the event pattern. The field names must also appear in the event with the same nesting structure.

When you write event patterns to match events, you can use the `TestEventPattern` API or the `test-event-pattern` CLI command to test that your pattern matches the correct events. For more information, see [TestEventPattern](https://docs.aws.amazon.com/AmazonCloudWatchEvents/latest/APIReference/API_TestEventPattern.html).

## Matching event values
<a name="eb-filtering-match-values"></a>

In an event pattern, the value to match is in a JSON array, surrounded by square brackets ("[", "]") so that you can provide multiple values. For example, to match events from Amazon EC2 or AWS Fargate, you could use the following pattern, which matches events where the value for the `"source"` field is either `"aws.ec2"` or `"aws.fargate"`.

```
{
    "source": ["aws.ec2", "aws.fargate"]
}
```

For more information, see [Matching on multiple field values](eb-event-patterns-arrays.md).

## Using comparison operators in Amazon EventBridge event patterns
<a name="eb-event-patterns-content-based-filtering"></a>

Amazon EventBridge supports declarative content filtering using event patterns. With content filtering, you can write complex event patterns that only match events under very specific conditions. For example, you can create an event pattern that matches an event when:
+ A field of the event is within a specific numeric range.
+ The event comes from a specific IP address.
+ A specific field doesn't exist in the event JSON.

For more information, see [Comparison operators](eb-create-pattern-operators.md).

## Considerations when creating event patterns
<a name="eb-create-pattern-considerations"></a>

Below are some things to consider when constructing your event patterns:
+ EventBridge ignores the fields in the event that aren't included in the event pattern. The effect is that there is a `"*": "*"` wildcard for fields that don't appear in the event pattern.
+ The values that event patterns match follow JSON rules. You can include strings enclosed in quotation marks ("), numbers, and the keywords `true`, `false`, and `null`.
+ For strings, EventBridge uses exact character-by-character matching without case-folding or any other string normalization.
+ For numbers, EventBridge uses string representation. For example, 300, 300.0, and 3.0e2 are not considered equal.
+ If multiple patterns are specified for the same JSON field, EventBridge only uses the last one.
+ Be aware that when EventBridge compiles event patterns for use, it uses dot (.) as the joining character.

  This means EventBridge will treat the following event patterns as identical:

  ```
  ## has no dots in keys
  { "detail" : { "state": { "status": [ "running" ] } } }
  
  ## has dots in keys
  { "detail" : { "state.status": [ "running" ] } }
  ```

  And that both event patterns will match the following two events: 

  ```
  ## has no dots in keys
  { "detail" : { "state": { "status": "running" } } }
  
  ## has dots in keys
  { "detail" : { "state.status": "running"  } }
  ```
**Note**  
This describes current EventBridge behavior, and should not be relied on to not change.
+ Event patterns containing duplicate fields are invalid. If a pattern contains duplicate fields, EventBridge only considers the final field value.

  For example, the following event patterns will match the same event:

  ```
  ## has duplicate keys
  {
    "source": ["aws.s3"],
    "source": ["aws.sns"],
    "detail-type": ["AWS API Call via CloudTrail"],
    "detail":  {
        "eventSource": ["s3.amazonaws.com"],
        "eventSource": ["sns.amazonaws.com"]
    }
  }
  
  ## has unique keys
  {
    "source": ["aws.sns"],
    "detail-type": ["AWS API Call via CloudTrail"],
    "detail": { "eventSource": ["sns.amazonaws.com"] }
  }
  ```

  And EventBridge treats the following two events as identical: 

  ```
  ## has duplicate keys
  {
    "source": ["aws.s3"],
    "source": ["aws.sns"],
    "detail-type": ["AWS API Call via CloudTrail"],
    "detail":  [
      {
        "eventSource": ["s3.amazonaws.com"],
        "eventSource": ["sns.amazonaws.com"]
      }
    ]
  }
  
  ## has unique keys
  {
    "source": ["aws.sns"],
    "detail-type": ["AWS API Call via CloudTrail"],
    "detail": [
      { "eventSource": ["sns.amazonaws.com"] }
    ]
  }
  ```
**Note**  
This describes current EventBridge behavior, and should not be relied on to not change.

# Matching events on event field values
<a name="eb-filtering-data-types"></a>

You can use all of the JSON data types and values to match events. The following examples show events and the event patterns that match them.

## Field matching
<a name="eb-filtering-example"></a>

You can match on the value of a field. Consider the following Amazon EC2 Auto Scaling event.

```
{
  "version": "0",
  "id": "3e3c153a-8339-4e30-8c35-687ebef853fe",
  "detail-type": "EC2 Instance Launch Successful",
  "source": "aws.autoscaling",
  "account": "123456789012",
  "time": "2015-11-11T21:31:47Z",
  "region": "us-east-1",
  "resources": [],
  "detail": {
    "eventVersion": "",
    "responseElements": null
  }
}
```

For the preceding event, you can use the `"responseElements"` field to match.

```
{
  "source": ["aws.autoscaling"],
  "detail-type": ["EC2 Instance Launch Successful"],
  "detail": {
   "responseElements": [null]
  }
}
```

## Value matching
<a name="eb-filtering-value-example"></a>

Consider the following Amazon Macie event, which is truncated.

```
{
  "version": "0",
  "id": "0948ba87-d3b8-c6d4-f2da-732a1example",
  "detail-type": "Macie Finding",
  "source": "aws.macie",
  "account": "123456789012",
  "time": "2021-04-29T23:12:15Z",
  "region":"us-east-1",
  "resources": [

  ],
  "detail": {
    "schemaVersion": "1.0",
    "id": "64b917aa-3843-014c-91d8-937ffexample",
    "accountId": "123456789012",
    "partition": "aws",
    "region": "us-east-1",
    "type": "Policy:IAMUser/S3BucketEncryptionDisabled",
    "title": "Encryption is disabled for the S3 bucket",
    "description": "Encryption is disabled for the Amazon S3 bucket. The data in the bucket isn’t encrypted 
        using server-side encryption.",
    "severity": {
        "score": 1,
        "description": "Low"
    },
    "createdAt": "2021-04-29T15:46:02Z",
    "updatedAt": "2021-04-29T23:12:15Z",
    "count": 2,
.
.
.
```

The following event pattern matches any event that has a severity score of 1 and a count of 2.

```
{
  "source": ["aws.macie"],
  "detail-type": ["Macie Finding"],
  "detail": {
    "severity": {
      "score": [1]
    },
    "count":[2]
  }
}
```

# Matching events on null values and empty strings in Amazon EventBridge
<a name="eb-event-patterns-null-values"></a>

**Important**  
In EventBridge, it is possible to create rules that can lead to higher-than-expected charges and throttling. For example, you can inadvertently create a rule that leads to an infinite loop, where a rule is fired recursively without end. Suppose you created a rule to detect that ACLs have changed on an Amazon S3 bucket, and trigger software to change them to the desired state. If the rule is not written carefully, the subsequent change to the ACLs fires the rule again, creating an infinite loop.  
For guidance on how to write precise rules and event patterns to minimize such unexpected results, see [Best practices for rules](eb-rules-best-practices.md) and [Best practices](eb-patterns-best-practices.md).

You can create an [event pattern](eb-event-patterns.md) that matches a field in an [event](eb-events.md) that has a null value or is an empty string. Consider the following example event.

See best practices to avoid higher than expected charges and throttling

```
{
  "version": "0",
  "id": "3e3c153a-8339-4e30-8c35-687ebef853fe",
  "detail-type": "EC2 Instance Launch Successful",
  "source": "aws.autoscaling",
  "account": "123456789012",
  "time": "2015-11-11T21:31:47Z",
  "region": "us-east-1",
  "resources": [
   ],
  "detail": {
    "eventVersion": "",
    "responseElements": null
   }
}
```

To match events where the value of `eventVersion` is an empty string, use the following event pattern, which matches the preceding event.

```
{
  "detail": {
     "eventVersion": [""]
  }
}
```

To match events where the value of `responseElements` is null, use the following event pattern, which matches the preceding event.

```
{
  "detail": {
     "responseElements": [null]
  }
}
```

**Note**  
Null values and empty strings are not interchangeable in pattern matching. An event pattern that matches empty strings doesn't match values of `null`.

## Using null values in AWS CloudFormation templates
<a name="eb-event-patterns-null-values-cfn"></a>

AWS CloudFormation does not allow `null` values in templates. If you define an event pattern with a null value using YAML or JSON object syntax, the template validation fails with the error: `'null' values are not allowed in templates`.

To work around this limitation, specify the `EventPattern` property as a JSON string instead of a YAML or JSON object. The following example shows how to match on null values in a AWS CloudFormation template:

```
MyRule:
  Type: AWS::Events::Rule
  Properties:
    EventPattern: '{"detail":{"responseElements":[null]}}'
```

# Matching on multiple values for an event field in Amazon EventBridge
<a name="eb-event-patterns-arrays"></a>

The value of each field in an [event pattern](eb-event-patterns.md) is an array containing one or more values. An event pattern matches the [event](eb-events.md) if any of the values in the array match the value in the event. If the value in the event is an array, then the event pattern matches if the intersection of the event pattern array and the event array is non-empty.

**Important**  
In EventBridge, it is possible to create rules that can lead to higher-than-expected charges and throttling. For example, you can inadvertently create a rule that leads to an infinite loop, where a rule is fired recursively without end. Suppose you created a rule to detect that ACLs have changed on an Amazon S3 bucket, and trigger software to change them to the desired state. If the rule is not written carefully, the subsequent change to the ACLs fires the rule again, creating an infinite loop.  
For guidance on how to write precise rules and event patterns to minimize such unexpected results, see [Best practices for rules](eb-rules-best-practices.md) and [Best practices](eb-patterns-best-practices.md).

For example, consider an event pattern that includes the following field.

```
"resources": [
   "arn:aws:ec2:us-east-1:123456789012:instance/i-b188560f",
   "arn:aws:ec2:us-east-1:111122223333:instance/i-b188560f",
   "arn:aws:ec2:us-east-1:444455556666:instance/i-b188560f",
]
```

The preceding event pattern matches an event that includes the following field because the first item in the event pattern array matches the second item in the event array.

```
"resources": [
   "arn:aws:autoscaling:us-east-1:123456789012:autoScalingGroup:eb56d16b-bbf0-401d-b893-d5978ed4a025:autoScalingGroupName/ASGTerminate",
   "arn:aws:ec2:us-east-1:123456789012:instance/i-b188560f" 
]
```

# Comparison operators for use in event patterns in Amazon EventBridge
<a name="eb-create-pattern-operators"></a>

Below a summary of all the comparison operators available in EventBridge. 

Comparison operators only work on leaf nodes, with the exception of `$or` and `anything-but`. 


| **Comparison** | **Example** | **Rule syntax** | **Event bus support** | **Pipe support** | 
| --- | --- | --- | --- | --- | 
|  And  |  Location is "New York" and Day is "Monday"  |  `"Location": [ "New York" ], "Day": ["Monday"]`  |  Yes  |  Yes  | 
| [Anything-but](#eb-filtering-anything-but) | State is any value besides "initializing". | `"state": [ { "anything-but": "initializing" } ]` |  Yes  |  Yes  | 
| [Anything-but (begins with)](#eb-filtering-anything-but-prefix) | Region is not in the US. |  `"Region": [ { "anything-but": {"prefix": "us-" } } ]`  |  Yes  |  No  | 
| [Anything-but (ends with)](#eb-filtering-anything-but-suffix) | FileName does not end with a .png extension. |  `"FileName": [ { "anything-but": { "suffix": ".png" } } ]`  |  Yes  |  No  | 
| [Anything-but (ignore case)](#eb-filtering-anything-but-ignore-case) | State is any value besides "initializing" or any other casing variation, such as "INITIALIZING". | `"state": : [{ "anything-but": { "equals-ignore-case": "initializing" }}]}` |  Yes  |  No  | 
| [Anything-but using a wildcard](#eb-filtering-anything-but-wildcard) | FileName is not a file path that includes `/lib/`. |  `"FilePath" : [{ "anything-but": { "wildcard": "*/lib/*" }}]`  |  Yes  |  No  | 
|  [Begins with](#eb-filtering-prefix-matching)  |  Region is in the US.  |  `"Region": [ {"prefix": "us-" } ]`  |  Yes  |  Yes  | 
| Begins with (ignore case) | Service name starts with the letters "eventb", regardless of case. | `{"service" : [{ "prefix": { "equals-ignore-case": "eventb" }}]}` |  Yes  |  Yes  | 
|  [Empty](eb-event-patterns-null-values.md)  |  LastName is empty.  |  `"LastName": [""]`  |  Yes  |  Yes  | 
|  Equals  |  Name is "Alice"  |  `"Name": [ "Alice" ]`  |  Yes  |  Yes  | 
|  [Equals (ignore case)](#eb-filtering-equals-ignore-case-matching)  |  Name is "Alice"  |  `"Name": [ { "equals-ignore-case": "alice" } ]`  |  Yes  |  Yes  | 
|  [Ends with](#eb-filtering-suffix-matching)  |  FileName ends with a .png extension  |  `"FileName": [ { "suffix": ".png" } ]`  |  Yes  |  Yes  | 
| Ends with (ignore case) | Service name ends with the letters "tbridge", or any other casing variation, such as "TBRIDGE". | `{"service" : [{ "suffix": { "equals-ignore-case": "tBridge" }}]}` |  Yes  |  Yes  | 
|  [Exists](#eb-filtering-exists-matching)  |  ProductName exists  |  `"ProductName": [ { "exists": true } ]`  |  Yes  |  Yes  | 
|  [Does not exist](#eb-filtering-exists-matching)  |  ProductName does not exist  |  `"ProductName": [ { "exists": false } ]`  |  Yes  |  Yes  | 
|  [Not](#eb-filtering-anything-but)  |  Weather is anything but "Raining"  |  `"Weather": [ { "anything-but": [ "Raining" ] } ]`  |  Yes  |  Yes  | 
|  [Null](eb-event-patterns-null-values.md)  |  UserID is null  |  `"UserID": [ null ]`  |  Yes  |  Yes  | 
|  [Numeric (equals)](#filtering-numeric-matching)  |  Price is 100  |  `"Price": [ { "numeric": [ "=", 100 ] } ]`  |  Yes  |  Yes  | 
|  [Numeric (range)](#filtering-numeric-matching)  |  Price is more than 10, and less than or equal to 20  |  `"Price": [ { "numeric": [ ">", 10, "<=", 20 ] } ]`  |  Yes  |  Yes  | 
|  Or  |  PaymentType is "Credit" or "Debit"  |  `"PaymentType": [ "Credit", "Debit"]`  |  Yes  |  Yes  | 
|  [Or (multiple fields)](#eb-filtering-complex-example-or)  |  Location is "New York", or Day is "Monday".  |  `"$or": [ { "Location": [ "New York" ] }, { "Day": [ "Monday" ] } ]`  |  Yes  |  Yes  | 
|  [Wildcard](#eb-filtering-wildcard-matching)  |  Any file with a .png extension, located within the folder "dir"  |  `"FileName": [ { "wildcard": "dir/*.png" } ] `  |  Yes  |  No  | 

## Prefix matching
<a name="eb-filtering-prefix-matching"></a>

You can match an event depending on the prefix of a value in the event source. You can use prefix matching for string values.

For example, the following event pattern would match any event where the `"time"` field started with `"2017-10-02"` such as `"time": "2017-10-02T18:43:48Z"`. 

```
{
  "time": [ { "prefix": "2017-10-02" } ]
}
```

### Prefix matching while ignoring case
<a name="eb-filtering-prefix-matching-ignore-case"></a>

You can also match a prefix value regardless of the casing of the characters a value begins with, using `equals-ignore-case` in conjunction with `prefix.`

For example, the following event pattern would match any event where the `service` field started with the character string `EventB`, but also `EVENTB`, `eventb`, or any other capitalization of those characters.

```
{
  "detail": {"service" : [{ "prefix": { "equals-ignore-case": "EventB" }}]}
}
```

## Suffix matching
<a name="eb-filtering-suffix-matching"></a>

You can match an event depending on the suffix of a value in the event source. You can use suffix matching for string values.

For example, the following event pattern would match any event where the `"FileName"` field ends with the `.png` file extension. 

```
{
  "FileName": [ { "suffix": ".png" } ]
}
```

### Suffix matching while ignoring case
<a name="eb-filtering-suffix-matching-ignore-case"></a>

You can also match a suffix value regardless of the casing of the characters a value ends with, using `equals-ignore-case` in conjunction with `suffix.`

For example, the following event pattern would match any event where the `FileName` field ended with the character string `.png`, but also `.PNG` or any other capitalization of those characters.

```
{
  "detail": {"FileName" : [{ "suffix": { "equals-ignore-case": ".png" }}]}
}
```

## Anything-but matching
<a name="eb-filtering-anything-but"></a>

*Anything-but* matching matches anything except what's specified in the rule. 

You can use anything-but matching with strings and numeric values, including lists that contain only strings, or only numbers.

The following event pattern shows anything-but matching with strings and numbers.

```
{
  "detail": {
    "state": [ { "anything-but": "initializing" } ]
  }
}

{
  "detail": {
    "x-limit": [ { "anything-but": 123 } ]
  }
}
```

The following event pattern shows anything-but matching with a list of strings.

```
{
  "detail": {
    "state": [ { "anything-but": [ "stopped", "overloaded" ] } ]
  }
}
```

The following event pattern shows anything-but matching with a list of numbers.

```
{
  "detail": {
    "x-limit": [ { "anything-but": [ 100, 200, 300 ] } ]
  }
}
```

### Anything-but matching while ignoring case
<a name="eb-filtering-anything-but-ignore-case"></a>

You can also use `equals-ignore-case` in conjunction with `anything-but`, to match string values regardless of character casing.

The following event pattern matches `state` fields that do not contain the string "initializing", "INITIALIZING", "Initializing", or any other capitalization of those characters. 

```
{
  "detail": {"state" : [{ "anything-but": { "equals-ignore-case": "initializing" }}]}
}
```

You can use `equals-ignore-case` in conjunction with `anything-but` to match against a list of values as well:

```
{
  "detail": {"state" : [{ "anything-but": { "equals-ignore-case": ["initializing", "stopped"] }}]}
}
```

### Anything-but matching on prefixes
<a name="eb-filtering-anything-but-prefix"></a>

You can use `prefix` in conjunction with `anything-but` to match string values that do not start with the specified value. This includes single values, or a list of values.

The following event pattern shows anything-but matching that matches any event that does not have the prefix `"init"` in the `"state"` field.

```
{
  "detail": {
    "state": [ { "anything-but": { "prefix": "init" } } ]
  }
}
```

The following event pattern shows anything-but matching used with a list of prefix values. This event pattern matches any event that does not have either the prefix `"init"` or `"stop"` in the `"state"` field.

```
{
"detail": {
  "state" : [{ "anything-but": { "prefix": ["init", "stop"] } } ] }
  }
}
```

### Anything-but matching on suffixes
<a name="eb-filtering-anything-but-suffix"></a>

You can use `suffix` in conjunction with `anything-but` to match string values that do not end with the specified value. This includes single values, or a list of values.

The following event pattern matches any values for the `FileName` field that do not end with `.txt`.

```
{
  "detail": {
    "FileName": [ { "anything-but": { "suffix": ".txt" } } ]
  }
}
```

The following event pattern shows anything-but matching used with a list of suffix values. This event pattern matches any values for the `FileName` field that do not end with either `.txt` or `.rtf`.

```
{
  "detail": {
    "FileName": [ { "anything-but": { "suffix": [".txt", ".rtf"] } } ]
  }
}
```

### Anything-but matching using wildcards
<a name="eb-filtering-anything-but-wildcard"></a>

You can use the wildcard character (\$1) within the values you specify for anything-but matching. This includes single values, or a list of values.

The following event pattern matches any values for the `FileName` field that do not contain `/lib/`.

```
{
"detail": {
  "FilePath" : [{ "anything-but": { "wildcard": "*/lib/*" }}]
  }
}
```

The following event pattern shows anything-but matching used with a list of values including wildcards. This event pattern matches any values for the `FileName` field that do not contain either `/lib/` or `/bin/`.

```
{
"detail": {
  "FilePath" : [{ "anything-but": { "wildcard": ["*/lib/*", "*/bin/*"] }}]
  }
}
```

For more information, see [Matching using wildcards](#eb-filtering-wildcard-matching).

## Numeric matching
<a name="filtering-numeric-matching"></a>

Numeric matching works with values that are JSON numbers. It is limited to values between -5.0e9 and \$15.0e9 inclusive, with 15 digits of precision, or six digits to the right of the decimal point.

The following shows numeric matching for an event pattern that only matches events that are true for all fields. 

```
{
  "detail": {
    "c-count": [ { "numeric": [ ">", 0, "<=", 5 ] } ],
    "d-count": [ { "numeric": [ "<", 10 ] } ],
    "x-limit": [ { "numeric": [ "=", 3.018e2 ] } ]
  }
}
```

## IP address matching
<a name="eb-filtering-ip-matching"></a>

You can use IP address matching for IPv4 and IPv6 addresses. The following event pattern shows IP address matching to IP addresses that start with 10.0.0 and end with a number between 0 and 255.

```
{
  "detail": {
    "sourceIPAddress": [ { "cidr": "10.0.0.0/24" } ]
  }
}
```

## Exists matching
<a name="eb-filtering-exists-matching"></a>

*Exists matching* works on the presence or absence of a field in the JSON of the event.

Exists matching only works on leaf nodes. It does not work on intermediate nodes.

The following event pattern matches any event that has a `detail.state` field.

```
{
  "detail": {
    "state": [ { "exists": true  } ]
  }
}
```

The preceding event pattern matches the following event.

```
{
  "version": "0",
  "id": "7bf73129-1428-4cd3-a780-95db273d1602",
  "detail-type": "EC2 Instance State-change Notification",
  "source": "aws.ec2",
  "account": "123456789012",
  "time": "2015-11-11T21:29:54Z",
  "region": "us-east-1",
  "resources": ["arn:aws:ec2:us-east-1:123456789012:instance/i-abcd1111"],
  "detail": {
    "instance-id": "i-abcd1111",
    "state": "pending"
  }
}
```

The preceding event pattern does NOT match the following event because it doesn't have a `detail.state` field.

```
{
  "detail-type": [ "EC2 Instance State-change Notification" ],
  "resources": [ "arn:aws:ec2:us-east-1:123456789012:instance/i-02ebd4584a2ebd341" ],
  "detail": {
    "c-count" : {
       "c1" : 100
    }
  }
}
```

## Equals-ignore-case matching
<a name="eb-filtering-equals-ignore-case-matching"></a>

*Equals-ignore-case* matching works on string values regardless of case.

The following event pattern matches any event that has a `detail-type` field that matches the specified string, regardless of case.

```
{
  "detail-type": [ { "equals-ignore-case": "ec2 instance state-change notification" } ]
}
```

The preceding event pattern matches the following event.

```
{
  "detail-type": [ "EC2 Instance State-change Notification" ],
  "resources": [ "arn:aws:ec2:us-east-1:123456789012:instance/i-02ebd4584a2ebd341" ],
  "detail": {
    "c-count" : {
       "c1" : 100
    }
  }
}
```

## Matching using wildcards
<a name="eb-filtering-wildcard-matching"></a>

You can use the wildcard character (\$1) to match string values in event patterns.

**Note**  
Currently the wildcard character is supported in event bus rules only.

Considerations when using wildcards in your event patterns:
+ You can specify any number of wildcard characters in a given string value; however, consecutive wildcard characters are not supported.
+ EventBridge supports using the backslash character (\$1) to specify the literal \$1 and \$1 characters in wildcard filters:
  + The string `\*` represents the literal \$1 character
  + The string `\\` represents the literal \$1 character

  Using the backslash to escape other characters is not supported.

### Wildcards and event pattern complexity
<a name="eb-filtering-wildcard-matching-complexity"></a>

There is a limit to how complex a rule using wildcards can be. If a rule is too complex, EventBridge returns an `InvalidEventPatternException` when attempting to create the rule. If your rule generates such an error, consider using the guidance below to reduce the complexity of the event pattern:
+ **Reduce the number of wildcard characters used**

  Only use wildcard characters where you truly need to match against multiple possible values. For example, consider the following event pattern, where you want to match against event buses in the same Region:

  ```
  {
  "EventBusArn": [ { "wildcard": "*:*:*:*:*:event-bus/*" } ]
  }
  ```

  In the above case, many of the sections of the ARN will be directly based on the Region in which your event buses reside. So if you are using the `us-east-1` Region, a less complex pattern that still matches the desired values might be the following example:

  ```
  {
  "EventBusArn": [ { "wildcard": "arn:aws:events:us-east-1:*:event-bus/*" } ]
  }
  ```
+ **Reduce repeating character sequences that occur after a wildcard character**

  Having the same character sequence appear multiple times after the use of a wildcard increases the complexity of processing the event pattern. Recast your event pattern to minimize repeated sequences. For example, consider the following example, that matches on the file name `doc.txt` file for any user:

  ```
  {
  "FileName": [ { "wildcard": "/Users/*/dir/dir/dir/dir/dir/doc.txt" } ]
  }
  ```

  If you knew that the `doc.txt` file would only occur in the specified path, you could reduce the repeated character sequence in this way:

  ```
  {
  "FileName": [ { "wildcard": "/Users/*/doc.txt" } ]
  }
  ```

## Complex example with multiple matching
<a name="eb-filtering-complex-example"></a>

You can combine multiple matching criteria into a more complex event pattern. For example, the following event pattern combines `anything-but` and `numeric`.

```
{
  "time": [ { "prefix": "2017-10-02" } ],
  "detail": {
    "state": [ { "anything-but": "initializing" } ],
    "c-count": [ { "numeric": [ ">", 0, "<=", 5 ] } ],
    "d-count": [ { "numeric": [ "<", 10 ] } ],
    "x-limit": [ { "anything-but": [ 100, 200, 300 ] } ]
  }
}
```

**Note**  
When building event patterns, if you include a key more than once the last reference will be the one used to evaluate events. For example, for the following pattern:  

```
{
  "detail": {
    "location": [ { "prefix": "us-" } ],
    "location": [ { "anything-but": "us-east" } ]
  }
}
```
only `{ "anything-but": "us-east" }` will be taken into account when evaluating the `location`.

## Complex example with `$or` matching
<a name="eb-filtering-complex-example-or"></a>

You can also create complex event patterns that check to see if *any* field values match, across multiple fields. Use `$or` to create an event pattern that matches if any of the values for multiple fields are matched.

Note that you can include other filter types, such as [numeric matching](#filtering-numeric-matching) and [arrays](eb-event-patterns-arrays.md), in your pattern matching for individual fields in your `$or` construct.

The following event pattern matches if any of the following conditions are met:
+ The `c-count` field is greater than 0 or less than or equal to 5.
+ The `d-count` field is less than 10.
+ The `x-limit` field equals 3.018e2.

```
{
  "detail": {
    "$or": [
      { "c-count": [ { "numeric": [ ">", 0, "<=", 5 ] } ] },
      { "d-count": [ { "numeric": [ "<", 10 ] } ] },
      { "x-limit": [ { "numeric": [ "=", 3.018e2 ] } ] }
    ]
  }
}
```

**Note**  
APIs that accept an event pattern (such as `PutRule`, `CreateArchive`, `UpdateArchive`, and `TestEventPattern`) will throw an `InvalidEventPatternException` if the use of `$or` results in over 1000 rule combinations.  
To determine the number of rule combinations in an event pattern, multiply the total number of arguments from each `$or` array in the event pattern. For example, the above pattern contains a single `$or` array with three arguments, so the total number of rule combinations is also three. If you added another `$or` array with two arguments, the total rule combinations would then be six.

# Best practices for Amazon EventBridge event patterns
<a name="eb-patterns-best-practices"></a>

Below are some best practices to consider when defining event patterns in your event bus rules.

## Avoid writing infinite loops
<a name="eb-patterns-best-practices-loops"></a>

In EventBridge, it is possible to create rules that lead to infinite loops, where a rule is fired repeatedly. For example, a rule might detect that ACLs have changed on an S3 bucket, and trigger software to change them to the desired state. If the rule is not written carefully, the subsequent change to the ACLs fires the rule again, creating an infinite loop.

To prevent these issues, write the event patterns for your rules to be as precise as possible, so they only match the events you actually want sent to the target. In the above example, you would create an event pattern to match events so that the triggered actions do not re-fire the same rule. For example, create an event pattern in your rule that would match events only if ACLs are found to be in a bad state, instead of after any change. For more information, see [Make event patterns precise as possible](#eb-patterns-best-practices-precision) and [Scope your event patterns to account for event source updates](#eb-patterns-best-practices-future-proof).

An infinite loop can quickly cause higher than expected charges. It can also lead to throttling and delayed event delivery. You can monitor the upper bound of your invocation rates to be warned about unexpected spikes in volume.

Use budgeting to alert you when charges exceed your specified limit. For more information, see [Managing Your Costs with Budgets](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/budgets-managing-costs.html).

## Make event patterns precise as possible
<a name="eb-patterns-best-practices-precision"></a>

The more precise your event pattern, the more likely it will match only the events you actually want it to, and avoid unexpected matches when new events are added to an event source, or existing events are updated to include new properties.

Event patterns can include filters that match on:
+ Event metadata about the event, such as `source`, `detail-type`. `account`, or `region`.
+ Event data, this is, the fields inside the `detail` object.
+ Event content, or the actual values of the fields inside the `detail` object.

Most patterns are simple, such as specifying only `source` and `detail-type` filters. However, EventBridge patterns include the flexibility to filter on any key or value of the event. In addition, you can apply content filters such as `prefix` and `suffix` filters to improve the precision of your patterns. For more information, see [Using comparison operators in Amazon EventBridge event patterns](eb-create-pattern.md#eb-event-patterns-content-based-filtering).

### Specify event source and detail type as filters
<a name="eb-patterns-best-practices-source"></a>

You can reduce generating infinite loops and matching undesired events by making your event patterns more precise using the `source` and `detail-type` metadata fields.

When you need to match specific values within two or more fields, use the `$or` comparison operator, rather than listing all possible values within a single array of values.

For events that are delivered through AWS CloudTrail, we recommend you use the `eventName` field as a filter.

The following event pattern example matches `CreateQueue` or `SetQueueAttributes` from the Amazon Simple Queue Service service, or `CreateKey` or `DisableKeyRotation` events from the AWS Key Management Service service.

```
{
  "detail-type": ["AWS API Call via CloudTrail"],
  "$or": [{
      "source": [
        "aws.sqs"
        ],
      "detail": {
        "eventName": [
          "CreateQueue",
          "SetQueueAttributes"
        ]
      }
    },
    {
      "source": [
        "aws.kms"
        ],
      "detail": {
        "eventName": [
          "CreateKey",
          "DisableKeyRotation"
        ]
      }
    }
  ]
}
```

### Specify account and region as filters
<a name="eb-patterns-best-practices-accounts-regions"></a>

Including `account` and `region` fields in your event pattern helps limit cross-account or cross-region event matching. 

### Specify content filters
<a name="eb-patterns-best-practices-content"></a>

Content-based filtering can help improve event pattern precision, while still keeping the length of the event pattern to a minimum. For example, matching based on a numeric range can be helpful instead of listing all possible numeric values.

For more information, see [Using comparison operators in Amazon EventBridge event patterns](eb-create-pattern.md#eb-event-patterns-content-based-filtering).

## Scope your event patterns to account for event source updates
<a name="eb-patterns-best-practices-future-proof"></a>

When creating event patterns, you should take into account that event schemas and event domains may evolve and expand over time. Here again, making your event patterns as precise as possible helps you limit unexpected matches if the event source changes or expands.

For example, suppose you are matching against events from a new micro-service that publishes payment-related events. Initially, the service uses the domain `acme.payments`, and publishes a single event, `Payment accepted`:

```
{
  "detail-type": "Payment accepted",
  "source": "acme.payments",
  "detail": {
    "type": "credit",
    "amount": "100",
    "date": "2023-06-10",
    "currency": "USD"
    }
  }
}
```

At this point, you could create a simple event pattern that matches Payment accepted events:

```
{ “source” : “acme.payments” }
```

However, suppose the service later introduces a new event for rejected payments:

```
{
  "detail-type": "Payment rejected",
  "source": "acme.payments",
  "detail": {
  }
}
```

In this case, the simple event pattern you created will now match against both `Payment accepted` and `Payment rejected` events. EventBridge routes both types of events to the specified target for processing, possibly introducing processing failures and additional processing cost.

To scope your event pattern to only `Payment accepted` events, you'd want to specify both `source` and `detail-type`, at a minimum:

```
{
  "detail-type": "Payment accepted",
  "source": "acme.payments"
  }
}
```

You can also specify account and Region in your event pattern, to further limit when cross-account or cross-Region events match this rule.

```
{
  "account": "012345678910",
  "source": "acme.payments",
  "region": "AWS-Region",
  "detail-type": "Payment accepted"
}
```

## Validate event patterns
<a name="eb-patterns-best-practices-validate"></a>

To ensure rules match the desired events, we strongly recommend you validate your event patterns. You can validate your event patterns using the EventBridge console or API:
+ In the EventBridge console, you can create and test event patterns [as part of creating a rule](eb-create-rule-visual.md), or separately by [using the Sandbox](eb-event-pattern-sandbox.md).
+ You can test your event patterns in the AWS CLI using the [test-event-pattern](https://docs.aws.amazon.com/cli/latest/reference/events/test-event-pattern.html) command.