Sub topic 5
Rules: connecting a bus to targets
This chapter assumes you can use the AWS CLI, read JSON, understand IAM roles and policies, and have used Lambda, SQS, or SNS. It also assumes you know what an event bus is and what an event looks like. Here you will learn how a rule links a bus to its targets, how to create and manage rules, and which errors come up most often.
What a rule is
A rule is a resource attached to exactly one event bus. It holds two things:
- A matching condition, which is either an event pattern or a schedule.
- Up to five targets, which are the services that receive matching events.
When an event arrives on the bus, EventBridge compares it with every enabled rule on that bus. Each rule that matches sends a copy of the event to each of its targets. Rules are independent of each other. One event can match many rules, and each match is delivered separately. A rule that does not match has no effect on the others.
A rule never changes the original event. It only decides who gets a copy. Any reshaping happens per target, through an input transformer, which a later chapter covers.
Rule types
A rule is one of two kinds, depending on what triggers it.
| Kind | Trigger | Where it works |
|---|---|---|
| Event pattern rule | An event that matches the pattern | Any bus |
| Scheduled rule | A rate or cron expression | The default bus only |
This chapter focuses on event pattern rules. A later chapter covers scheduled rules and EventBridge Scheduler, the newer service for schedules.
Creating a rule
Creating a rule and attaching targets are two separate API calls. put-rule defines the rule, and put-targets attaches the targets.
Save this pattern as pattern.json:
{
"source": ["com.example.orders"],
"detail-type": ["OrderPlaced"],
"detail": {
"amount": [{ "numeric": [">=", 100] }],
"status": [{ "anything-but": ["test"] }]
}
}This pattern matches OrderPlaced events from com.example.orders whose detail.amount is at least 100 and whose detail.status is not "test". Now create the rule and attach targets from targets.json:
aws events put-rule --name high-value-orders --event-bus-name orders-bus --event-pattern file://pattern.json
aws events put-targets --rule high-value-orders --event-bus-name orders-bus --targets file://targets.jsonAlways pass --event-bus-name when you work with a custom bus. If you leave it out, the CLI uses the default bus. The command then creates a second rule with the same name on the wrong bus, and no error warns you.
put-rule returns the rule ARN. It also accepts these options:
--descriptionstores free text that explains the rule.--stateisENABLED(the default) orDISABLED.--role-arnis needed only for specific cases, such as a rule that sends events to another bus. The permissions chapter covers this.
The targets file
The targets.json file holds a list of target objects. A minimal Lambda target needs only an Id and an Arn:
[
{
"Id": "process-order-fn",
"Arn": "arn:aws:lambda:us-east-1:123456789012:function:process-order"
}
]Id must be unique within the rule. It can contain letters, numbers, periods, hyphens, and underscores, up to 64 characters. The Arn identifies the destination. Each target type may also accept settings such as RoleArn, InputTransformer, RetryPolicy, and DeadLetterConfig.
put-rule is an upsert
put-rule creates a rule if the name is new and replaces it if the name exists on that bus. This lets you run the same command repeatedly in a deployment script. It also means a typo in the name can overwrite a rule you did not intend to change.
put-targets behaves similarly for target IDs. A target with an existing Id is replaced, and a new Id is added. Targets that you leave out of the call are not removed. To remove them, call remove-targets explicitly.
Managing rules
These commands cover the lifecycle of a rule:
| Task | Command |
|---|---|
| List rules on a bus | `aws events list-rules --event-bus-name orders-bus` |
| Show one rule | `aws events describe-rule --name high-value-orders --event-bus-name orders-bus` |
| List a rule's targets | `aws events list-targets-by-rule --rule high-value-orders --event-bus-name orders-bus` |
| Stop matching without deleting | `aws events disable-rule --name high-value-orders --event-bus-name orders-bus` |
| Resume matching | `aws events enable-rule --name high-value-orders --event-bus-name orders-bus` |
| Remove a target | `aws events remove-targets --rule high-value-orders --event-bus-name orders-bus --ids process-order-fn` |
| Delete a rule | `aws events delete-rule --name high-value-orders --event-bus-name orders-bus` |
delete-rule fails while the rule still has targets. Remove the targets first.
A disabled rule is useful for incident response. You can stop a noisy integration at once and keep its configuration. Events that arrive while the rule is disabled are not queued for it. Once you enable the rule again, it only sees new events. If you need to recover missed events, use archive and replay, which a later chapter covers.
Limits and behavior to know
- A rule has at most five targets. If you need more consumers, point one target at an SNS topic or another event bus and fan out from there.
- Each account has a quota on rules per bus. The default is 300, and you can ask for an increase.
- A rule has one event pattern. To match two unrelated shapes of event, either write one pattern with several values in an array, or create two rules.
- A rule matches only events on its own bus. A rule on the default bus never sees events sent to
orders-bus. - Matching is at-least-once. A target can occasionally receive the same event twice, so make consumers idempotent.
- Delivery order between events is not guaranteed.
Multiple rules, one event
Because rules are independent, you can build several consumers around the same event without coordination. A single OrderPlaced event could feed:
- A rule that sends every order to an analytics queue.
- A rule that sends orders of 100 or more to a fulfillment Lambda function.
- A rule that sends orders with a
statusof"flagged"to a review topic.
An order with an amount of 250 and a status of "new" matches the first two rules. It does not match the third.
Permissions at a glance
Creating the rule is not enough for delivery to work. The rule must have permission to call each target.
- For Lambda, SQS, SNS, and several other services, you attach a resource-based policy to the target. It allows
events.amazonaws.comto invoke or send to it, usually restricted to the rule ARN withaws:SourceArn. - For services that use IAM roles, such as Step Functions, Kinesis, and ECS tasks, you set
RoleArnon the target. The role must trustevents.amazonaws.com.
When you create targets in the console, EventBridge adds the resource policy for you. When you use the CLI, CloudFormation, or other tools, it does not. This is the most common reason a CLI-built rule appears healthy but delivers nothing.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Rule never triggers | Rule is on a different bus than the one receiving events | Compare `EventBusName` in `put-events` with `--event-bus-name` on the rule |
| Rule never triggers | Pattern does not match the event | Run `aws events test-event-pattern` with a sample event |
| `MatchedEvents` rises but the target does nothing | Missing resource policy or role | Add the permission, then check `FailedInvocations` |
| `put-rule` returns `InvalidEventPatternException` | Invalid JSON or an unsupported operator | Validate the file and check operator names and nesting |
| Wrong rule updated | `put-rule` replaced an existing rule with the same name | Use unique names and check with `describe-rule` first |
| `delete-rule` fails | Targets still attached | Run `remove-targets` for each ID |
| `put-targets` reports `FailedEntryCount` above 0 | Invalid target settings or too many targets | Read the `ErrorCode` and `ErrorMessage` in `FailedEntries` |
Like put-events, put-targets can succeed as a call while individual entries fail. Check FailedEntryCount in the response, especially in scripts.
Verifying a rule end to end
- Confirm the rule exists on the right bus with
describe-rule. - Confirm the targets with
list-targets-by-rule. - Check the pattern against a sample event with
aws events test-event-pattern. - Publish a real test event to the same bus.
- Look at the rule's
MatchedEvents,Invocations, andFailedInvocationsmetrics in CloudWatch, and at the target's own logs.
MatchedEvents tells you the pattern worked. Invocations and FailedInvocations tell you whether delivery worked. Checking them separates a pattern problem from a permission problem.
Exercise
You run aws events put-rule --name audit-orders --event-pattern file://pattern.json and then publish events to a custom bus named orders-bus. The rule never triggers, and aws events list-rules --event-bus-name orders-bus does not show it. What went wrong, and how do you fix it?
Show answer
The command did not include --event-bus-name, so the rule was created on the default bus. Rules match only events on their own bus. Delete the rule from the default bus (remove its targets first), then create it again with --event-bus-name orders-bus, and attach the targets to that bus.
Exercise
A rule on orders-bus shows MatchedEvents of 40 and Invocations of 40, but FailedInvocations is also 40. The target is a Lambda function created through the CLI. What is the most likely cause?
Show answer
The pattern works, because events matched. Delivery fails because the Lambda function has no resource-based policy that lets events.amazonaws.com invoke it. Add one with aws lambda add-permission, using the rule ARN as the source ARN.