UNPKG

9.02 kBMarkdownView Raw
1# Amazon EventBridge Construct Library
2<!--BEGIN STABILITY BANNER-->
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<!--END STABILITY BANNER-->
13
14Amazon EventBridge delivers a near real-time stream of system events that
15describe changes in AWS resources. For example, an AWS CodePipeline emits the
16[State
17Change](https://docs.aws.amazon.com/eventbridge/latest/userguide/event-types.html#codepipeline-event-type)
18event 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
47The `Rule` construct defines an EventBridge rule which monitors an
48event based on an [event
49pattern](https://docs.aws.amazon.com/eventbridge/latest/userguide/filtering-examples-structure.html)
50and invoke __event targets__ when the pattern is matched against a triggered
51event. Event targets are objects that implement the `IRuleTarget` interface.
52
53Normally, you will use one of the `source.onXxx(name[, target[, options]]) ->
54Rule` methods on the event source to define an event rule associated with
55the specific activity. You can targets either via props, or add targets using
56`rule.addTarget`.
57
58For example, to define an rule that triggers a CodeBuild project build when a
59commit is pushed to the "master" branch of a CodeCommit repository:
60
61```ts
62declare const repo: codecommit.Repository;
63declare const project: codebuild.Project;
64
65const onCommitRule = repo.onCommit('OnCommit', {
66 target: new targets.CodeBuildProject(project),
67 branches: ['master']
68});
69```
70
71You can add additional targets, with optional [input
72transformer](https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_InputTransformer.html)
73using `eventRule.addTarget(target[, input])`. For example, we can add a SNS
74topic target which formats a human-readable message for the commit.
75
76For example, this adds an SNS topic as a target:
77
78```ts
79declare const onCommitRule: events.Rule;
80declare const topic: sns.Topic;
81
82onCommitRule.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
89Or using an Object:
90
91```ts
92declare const onCommitRule: events.Rule;
93declare const topic: sns.Topic;
94
95onCommitRule.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
106You can configure a Rule to run on a schedule (cron or rate).
107Rate must be specified in minutes, hours or days.
108
109The following example runs a task every day at 4am:
110
111```ts fixture=basic
112import { Rule, Schedule } from '@aws-cdk/aws-events';
113import { EcsTask } from '@aws-cdk/aws-events-targets';
114import { Cluster, TaskDefinition } from '@aws-cdk/aws-ecs';
115import { Role } from '@aws-cdk/aws-iam';
116
117declare const cluster: Cluster;
118declare const taskDefinition: TaskDefinition;
119declare const role: Role;
120
121const ecsTaskTarget = new EcsTask({ cluster, taskDefinition, role });
122
123new Rule(this, 'ScheduleRule', {
124 schedule: Schedule.cron({ minute: '0', hour: '4' }),
125 targets: [ecsTaskTarget],
126});
127```
128
129If you want to specify Fargate platform version, set `platformVersion` in EcsTask's props like the following example:
130
131```ts
132declare const cluster: ecs.Cluster;
133declare const taskDefinition: ecs.TaskDefinition;
134declare const role: iam.Role;
135
136const platformVersion = ecs.FargatePlatformVersion.VERSION1_4;
137const ecsTaskTarget = new targets.EcsTask({ cluster, taskDefinition, role, platformVersion });
138```
139
140## Event Targets
141
142The `@aws-cdk/aws-events-targets` module includes classes that implement the `IRuleTarget`
143interface for various AWS services.
144
145The 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
161It's possible to have the source of the event and a target in separate AWS accounts and regions:
162
163```ts nofixture
164import { App, Stack } from '@aws-cdk/core';
165import * as codebuild from '@aws-cdk/aws-codebuild';
166import * as codecommit from '@aws-cdk/aws-codecommit';
167import * as targets from '@aws-cdk/aws-events-targets';
168
169const app = new App();
170
171const account1 = '11111111111';
172const account2 = '22222222222';
173
174const stack1 = new Stack(app, 'Stack1', { env: { account: account1, region: 'us-west-1' } });
175const repo = new codecommit.Repository(stack1, 'Repository', {
176 repositoryName: 'myrepository',
177});
178
179const stack2 = new Stack(app, 'Stack2', { env: { account: account2, region: 'us-east-1' } });
180const project = new codebuild.Project(stack2, 'Project', {
181 // ...
182});
183
184repo.onCommit('OnCommit', {
185 target: new targets.CodeBuildProject(project),
186});
187```
188
189In 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
197For 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
202It 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
205const bus = new events.EventBus(this, 'bus', {
206 eventBusName: 'MyCustomEventBus'
207});
208
209bus.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
221To import an existing EventBus into your CDK application, use `EventBus.fromEventBusArn`, `EventBus.fromEventBusAttributes`
222or `EventBus.fromEventBusName` factory method.
223
224Then, you can use the `grantPutEventsTo` method to grant `event:PutEvents` to the eventBus.
225
226```ts
227declare const lambdaFunction: lambda.Function;
228
229const 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
232eventBus.grantPutEventsTo(lambdaFunction);
233```