1 | # Amazon EventBridge Construct Library
|
2 |
|
3 |
|
4 | ---
|
5 |
|
6 | ![cfn-resources: Stable](https://img.shields.io/badge/cfn--resources-stable-success.svg?style=for-the-badge)
|
7 |
|
8 | ![cdk-constructs: Stable](https://img.shields.io/badge/cdk--constructs-stable-success.svg?style=for-the-badge)
|
9 |
|
10 | ---
|
11 |
|
12 |
|
13 |
|
14 | Amazon EventBridge delivers a near real-time stream of system events that
|
15 | describe changes in AWS resources. For example, an AWS CodePipeline emits the
|
16 | [State
|
17 | Change](https://docs.aws.amazon.com/eventbridge/latest/userguide/event-types.html#codepipeline-event-type)
|
18 | event when the pipeline changes its state.
|
19 |
|
20 | * __Events__: An event indicates a change in your AWS environment. AWS resources
|
21 | can generate events when their state changes. For example, Amazon EC2
|
22 | generates an event when the state of an EC2 instance changes from pending to
|
23 | running, and Amazon EC2 Auto Scaling generates events when it launches or
|
24 | terminates instances. AWS CloudTrail publishes events when you make API calls.
|
25 | You can generate custom application-level events and publish them to
|
26 | EventBridge. You can also set up scheduled events that are generated on
|
27 | a periodic basis. For a list of services that generate events, and sample
|
28 | events from each service, see [EventBridge Event Examples From Each
|
29 | Supported
|
30 | Service](https://docs.aws.amazon.com/eventbridge/latest/userguide/event-types.html).
|
31 | * __Targets__: A target processes events. Targets can include Amazon EC2
|
32 | instances, AWS Lambda functions, Kinesis streams, Amazon ECS tasks, Step
|
33 | Functions state machines, Amazon SNS topics, Amazon SQS queues, Amazon CloudWatch LogGroups, and built-in
|
34 | targets. A target receives events in JSON format.
|
35 | * __Rules__: A rule matches incoming events and routes them to targets for
|
36 | processing. A single rule can route to multiple targets, all of which are
|
37 | processed in parallel. Rules are not processed in a particular order. This
|
38 | enables different parts of an organization to look for and process the events
|
39 | that are of interest to them. A rule can customize the JSON sent to the
|
40 | target, by passing only certain parts or by overwriting it with a constant.
|
41 | * __EventBuses__: An event bus can receive events from your own custom applications
|
42 | or it can receive events from applications and services created by AWS SaaS partners.
|
43 | See [Creating an Event Bus](https://docs.aws.amazon.com/eventbridge/latest/userguide/create-event-bus.html).
|
44 |
|
45 | ## Rule
|
46 |
|
47 | The `Rule` construct defines an EventBridge rule which monitors an
|
48 | event based on an [event
|
49 | pattern](https://docs.aws.amazon.com/eventbridge/latest/userguide/filtering-examples-structure.html)
|
50 | and invoke __event targets__ when the pattern is matched against a triggered
|
51 | event. Event targets are objects that implement the `IRuleTarget` interface.
|
52 |
|
53 | Normally, you will use one of the `source.onXxx(name[, target[, options]]) ->
|
54 | Rule` methods on the event source to define an event rule associated with
|
55 | the specific activity. You can targets either via props, or add targets using
|
56 | `rule.addTarget`.
|
57 |
|
58 | For example, to define an rule that triggers a CodeBuild project build when a
|
59 | commit is pushed to the "master" branch of a CodeCommit repository:
|
60 |
|
61 | ```ts
|
62 | declare const repo: codecommit.Repository;
|
63 | declare const project: codebuild.Project;
|
64 |
|
65 | const onCommitRule = repo.onCommit('OnCommit', {
|
66 | target: new targets.CodeBuildProject(project),
|
67 | branches: ['master']
|
68 | });
|
69 | ```
|
70 |
|
71 | You can add additional targets, with optional [input
|
72 | transformer](https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_InputTransformer.html)
|
73 | using `eventRule.addTarget(target[, input])`. For example, we can add a SNS
|
74 | topic target which formats a human-readable message for the commit.
|
75 |
|
76 | For example, this adds an SNS topic as a target:
|
77 |
|
78 | ```ts
|
79 | declare const onCommitRule: events.Rule;
|
80 | declare const topic: sns.Topic;
|
81 |
|
82 | onCommitRule.addTarget(new targets.SnsTopic(topic, {
|
83 | message: events.RuleTargetInput.fromText(
|
84 | `A commit was pushed to the repository ${codecommit.ReferenceEvent.repositoryName} on branch ${codecommit.ReferenceEvent.referenceName}`
|
85 | )
|
86 | }));
|
87 | ```
|
88 |
|
89 | Or using an Object:
|
90 |
|
91 | ```ts
|
92 | declare const onCommitRule: events.Rule;
|
93 | declare const topic: sns.Topic;
|
94 |
|
95 | onCommitRule.addTarget(new targets.SnsTopic(topic, {
|
96 | message: events.RuleTargetInput.fromObject(
|
97 | {
|
98 | DataType: `custom_${events.EventField.fromPath('$.detail-type')}`
|
99 | }
|
100 | )
|
101 | }));
|
102 | ```
|
103 |
|
104 | ## Scheduling
|
105 |
|
106 | You can configure a Rule to run on a schedule (cron or rate).
|
107 | Rate must be specified in minutes, hours or days.
|
108 |
|
109 | The following example runs a task every day at 4am:
|
110 |
|
111 | ```ts fixture=basic
|
112 | import { Rule, Schedule } from '@aws-cdk/aws-events';
|
113 | import { EcsTask } from '@aws-cdk/aws-events-targets';
|
114 | import { Cluster, TaskDefinition } from '@aws-cdk/aws-ecs';
|
115 | import { Role } from '@aws-cdk/aws-iam';
|
116 |
|
117 | declare const cluster: Cluster;
|
118 | declare const taskDefinition: TaskDefinition;
|
119 | declare const role: Role;
|
120 |
|
121 | const ecsTaskTarget = new EcsTask({ cluster, taskDefinition, role });
|
122 |
|
123 | new Rule(this, 'ScheduleRule', {
|
124 | schedule: Schedule.cron({ minute: '0', hour: '4' }),
|
125 | targets: [ecsTaskTarget],
|
126 | });
|
127 | ```
|
128 |
|
129 | If you want to specify Fargate platform version, set `platformVersion` in EcsTask's props like the following example:
|
130 |
|
131 | ```ts
|
132 | declare const cluster: ecs.Cluster;
|
133 | declare const taskDefinition: ecs.TaskDefinition;
|
134 | declare const role: iam.Role;
|
135 |
|
136 | const platformVersion = ecs.FargatePlatformVersion.VERSION1_4;
|
137 | const ecsTaskTarget = new targets.EcsTask({ cluster, taskDefinition, role, platformVersion });
|
138 | ```
|
139 |
|
140 | ## Event Targets
|
141 |
|
142 | The `@aws-cdk/aws-events-targets` module includes classes that implement the `IRuleTarget`
|
143 | interface for various AWS services.
|
144 |
|
145 | The following targets are supported:
|
146 |
|
147 | * `targets.CodeBuildProject`: Start an AWS CodeBuild build
|
148 | * `targets.CodePipeline`: Start an AWS CodePipeline pipeline execution
|
149 | * `targets.EcsTask`: Start a task on an Amazon ECS cluster
|
150 | * `targets.LambdaFunction`: Invoke an AWS Lambda function
|
151 | * `targets.SnsTopic`: Publish into an SNS topic
|
152 | * `targets.SqsQueue`: Send a message to an Amazon SQS Queue
|
153 | * `targets.SfnStateMachine`: Trigger an AWS Step Functions state machine
|
154 | * `targets.BatchJob`: Queue an AWS Batch Job
|
155 | * `targets.AwsApi`: Make an AWS API call
|
156 | * `targets.ApiGateway`: Invoke an AWS API Gateway
|
157 | * `targets.ApiDestination`: Make an call to an external destination
|
158 |
|
159 | ### Cross-account and cross-region targets
|
160 |
|
161 | It's possible to have the source of the event and a target in separate AWS accounts and regions:
|
162 |
|
163 | ```ts nofixture
|
164 | import { App, Stack } from '@aws-cdk/core';
|
165 | import * as codebuild from '@aws-cdk/aws-codebuild';
|
166 | import * as codecommit from '@aws-cdk/aws-codecommit';
|
167 | import * as targets from '@aws-cdk/aws-events-targets';
|
168 |
|
169 | const app = new App();
|
170 |
|
171 | const account1 = '11111111111';
|
172 | const account2 = '22222222222';
|
173 |
|
174 | const stack1 = new Stack(app, 'Stack1', { env: { account: account1, region: 'us-west-1' } });
|
175 | const repo = new codecommit.Repository(stack1, 'Repository', {
|
176 | repositoryName: 'myrepository',
|
177 | });
|
178 |
|
179 | const stack2 = new Stack(app, 'Stack2', { env: { account: account2, region: 'us-east-1' } });
|
180 | const project = new codebuild.Project(stack2, 'Project', {
|
181 | // ...
|
182 | });
|
183 |
|
184 | repo.onCommit('OnCommit', {
|
185 | target: new targets.CodeBuildProject(project),
|
186 | });
|
187 | ```
|
188 |
|
189 | In this situation, the CDK will wire the 2 accounts together:
|
190 |
|
191 | * It will generate a rule in the source stack with the event bus of the target account as the target
|
192 | * It will generate a rule in the target stack, with the provided target
|
193 | * It will generate a separate stack that gives the source account permissions to publish events
|
194 | to the event bus of the target account in the given region,
|
195 | and make sure its deployed before the source stack
|
196 |
|
197 | For more information, see the
|
198 | [AWS documentation on cross-account events](https://docs.aws.amazon.com/eventbridge/latest/userguide/eventbridge-cross-account-event-delivery.html).
|
199 |
|
200 | ## Archiving
|
201 |
|
202 | It is possible to archive all or some events sent to an event bus. It is then possible to [replay these events](https://aws.amazon.com/blogs/aws/new-archive-and-replay-events-with-amazon-eventbridge/).
|
203 |
|
204 | ```ts
|
205 | const bus = new events.EventBus(this, 'bus', {
|
206 | eventBusName: 'MyCustomEventBus'
|
207 | });
|
208 |
|
209 | bus.archive('MyArchive', {
|
210 | archiveName: 'MyCustomEventBusArchive',
|
211 | description: 'MyCustomerEventBus Archive',
|
212 | eventPattern: {
|
213 | account: [Stack.of(this).account],
|
214 | },
|
215 | retention: Duration.days(365),
|
216 | });
|
217 | ```
|
218 |
|
219 | ## Granting PutEvents to an existing EventBus
|
220 |
|
221 | To import an existing EventBus into your CDK application, use `EventBus.fromEventBusArn`, `EventBus.fromEventBusAttributes`
|
222 | or `EventBus.fromEventBusName` factory method.
|
223 |
|
224 | Then, you can use the `grantPutEventsTo` method to grant `event:PutEvents` to the eventBus.
|
225 |
|
226 | ```ts
|
227 | declare const lambdaFunction: lambda.Function;
|
228 |
|
229 | const eventBus = events.EventBus.fromEventBusArn(this, 'ImportedEventBus', 'arn:aws:events:us-east-1:111111111:event-bus/my-event-bus');
|
230 |
|
231 | // now you can just call methods on the eventbus
|
232 | eventBus.grantPutEventsTo(lambdaFunction);
|
233 | ```
|