UNPKG

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