UNPKG

9.48 kBMarkdownView Raw
1# Event Targets for Amazon EventBridge
2<!--BEGIN STABILITY BANNER-->
3
4---
5
6![cdk-constructs: Stable](https://img.shields.io/badge/cdk--constructs-stable-success.svg?style=for-the-badge)
7
8---
9
10<!--END STABILITY BANNER-->
11
12This library contains integration classes to send Amazon EventBridge to any
13number of supported AWS Services. Instances of these classes should be passed
14to the `rule.addTarget()` method.
15
16Currently supported are:
17
18* [Start a CodeBuild build](#start-a-codebuild-build)
19* [Start a CodePipeline pipeline](#start-a-codepipeline-pipeline)
20* Run an ECS task
21* [Invoke a Lambda function](#invoke-a-lambda-function)
22* [Invoke a API Gateway REST API](#invoke-an-api-gateway-rest-api)
23* Publish a message to an SNS topic
24* Send a message to an SQS queue
25* [Start a StepFunctions state machine](#start-a-stepfunctions-state-machine)
26* [Queue a Batch job](#queue-a-batch-job)
27* Make an AWS API call
28* Put a record to a Kinesis stream
29* [Log an event into a LogGroup](#log-an-event-into-a-loggroup)
30* Put a record to a Kinesis Data Firehose stream
31* [Put an event on an EventBridge bus](#put-an-event-on-an-eventbridge-bus)
32* [Send an event to EventBridge API Destination](#invoke-an-api-destination)
33
34See the README of the `@aws-cdk/aws-events` library for more information on
35EventBridge.
36
37## Event retry policy and using dead-letter queues
38
39The Codebuild, CodePipeline, Lambda, StepFunctions, LogGroup and SQSQueue targets support attaching a [dead letter queue and setting retry policies](https://docs.aws.amazon.com/eventbridge/latest/userguide/rule-dlq.html). See the [lambda example](#invoke-a-lambda-function).
40Use [escape hatches](https://docs.aws.amazon.com/cdk/latest/guide/cfn_layer.html) for the other target types.
41
42## Invoke a Lambda function
43
44Use the `LambdaFunction` target to invoke a lambda function.
45
46The code snippet below creates an event rule with a Lambda function as a target
47triggered for every events from `aws.ec2` source. You can optionally attach a
48[dead letter queue](https://docs.aws.amazon.com/eventbridge/latest/userguide/rule-dlq.html).
49
50```ts
51import * as lambda from '@aws-cdk/aws-lambda';
52
53const fn = new lambda.Function(this, 'MyFunc', {
54 runtime: lambda.Runtime.NODEJS_12_X,
55 handler: 'index.handler',
56 code: lambda.Code.fromInline(`exports.handler = handler.toString()`),
57});
58
59const rule = new events.Rule(this, 'rule', {
60 eventPattern: {
61 source: ["aws.ec2"],
62 },
63});
64
65const queue = new sqs.Queue(this, 'Queue');
66
67rule.addTarget(new targets.LambdaFunction(fn, {
68 deadLetterQueue: queue, // Optional: add a dead letter queue
69 maxEventAge: cdk.Duration.hours(2), // Optional: set the maxEventAge retry policy
70 retryAttempts: 2, // Optional: set the max number of retry attempts
71}));
72```
73
74## Log an event into a LogGroup
75
76Use the `LogGroup` target to log your events in a CloudWatch LogGroup.
77
78For example, the following code snippet creates an event rule with a CloudWatch LogGroup as a target.
79Every events sent from the `aws.ec2` source will be sent to the CloudWatch LogGroup.
80
81```ts
82import * as logs from '@aws-cdk/aws-logs';
83
84const logGroup = new logs.LogGroup(this, 'MyLogGroup', {
85 logGroupName: 'MyLogGroup',
86});
87
88const rule = new events.Rule(this, 'rule', {
89 eventPattern: {
90 source: ["aws.ec2"],
91 },
92});
93
94rule.addTarget(new targets.CloudWatchLogGroup(logGroup));
95```
96
97## Start a CodeBuild build
98
99Use the `CodeBuildProject` target to trigger a CodeBuild project.
100
101The code snippet below creates a CodeCommit repository that triggers a CodeBuild project
102on commit to the master branch. You can optionally attach a
103[dead letter queue](https://docs.aws.amazon.com/eventbridge/latest/userguide/rule-dlq.html).
104
105```ts
106import * as codebuild from '@aws-cdk/aws-codebuild';
107import * as codecommit from '@aws-cdk/aws-codecommit';
108
109const repo = new codecommit.Repository(this, 'MyRepo', {
110 repositoryName: 'aws-cdk-codebuild-events',
111});
112
113const project = new codebuild.Project(this, 'MyProject', {
114 source: codebuild.Source.codeCommit({ repository: repo }),
115});
116
117const deadLetterQueue = new sqs.Queue(this, 'DeadLetterQueue');
118
119// trigger a build when a commit is pushed to the repo
120const onCommitRule = repo.onCommit('OnCommit', {
121 target: new targets.CodeBuildProject(project, {
122 deadLetterQueue: deadLetterQueue,
123 }),
124 branches: ['master'],
125});
126```
127
128## Start a CodePipeline pipeline
129
130Use the `CodePipeline` target to trigger a CodePipeline pipeline.
131
132The code snippet below creates a CodePipeline pipeline that is triggered every hour
133
134```ts
135import * as codepipeline from '@aws-cdk/aws-codepipeline';
136
137const pipeline = new codepipeline.Pipeline(this, 'Pipeline');
138
139const rule = new events.Rule(this, 'Rule', {
140 schedule: events.Schedule.expression('rate(1 hour)'),
141});
142
143rule.addTarget(new targets.CodePipeline(pipeline));
144```
145
146## Start a StepFunctions state machine
147
148Use the `SfnStateMachine` target to trigger a State Machine.
149
150The code snippet below creates a Simple StateMachine that is triggered every minute with a
151dummy object as input.
152You can optionally attach a
153[dead letter queue](https://docs.aws.amazon.com/eventbridge/latest/userguide/rule-dlq.html)
154to the target.
155
156```ts
157import * as iam from '@aws-cdk/aws-iam';
158import * as sfn from '@aws-cdk/aws-stepfunctions';
159
160const rule = new events.Rule(this, 'Rule', {
161 schedule: events.Schedule.rate(cdk.Duration.minutes(1)),
162});
163
164const dlq = new sqs.Queue(this, 'DeadLetterQueue');
165
166const role = new iam.Role(this, 'Role', {
167 assumedBy: new iam.ServicePrincipal('events.amazonaws.com'),
168});
169const stateMachine = new sfn.StateMachine(this, 'SM', {
170 definition: new sfn.Wait(this, 'Hello', { time: sfn.WaitTime.duration(cdk.Duration.seconds(10)) })
171});
172
173rule.addTarget(new targets.SfnStateMachine(stateMachine, {
174 input: events.RuleTargetInput.fromObject({ SomeParam: 'SomeValue' }),
175 deadLetterQueue: dlq,
176 role: role
177}));
178```
179
180## Queue a Batch job
181
182Use the `BatchJob` target to queue a Batch job.
183
184The code snippet below creates a Simple JobQueue that is triggered every hour with a
185dummy object as input.
186You can optionally attach a
187[dead letter queue](https://docs.aws.amazon.com/eventbridge/latest/userguide/rule-dlq.html)
188to the target.
189
190```ts
191import * as batch from '@aws-cdk/aws-batch';
192import { ContainerImage } from '@aws-cdk/aws-ecs';
193
194const jobQueue = new batch.JobQueue(this, 'MyQueue', {
195 computeEnvironments: [
196 {
197 computeEnvironment: new batch.ComputeEnvironment(this, 'ComputeEnvironment', {
198 managed: false,
199 }),
200 order: 1,
201 },
202 ],
203});
204
205const jobDefinition = new batch.JobDefinition(this, 'MyJob', {
206 container: {
207 image: ContainerImage.fromRegistry('test-repo'),
208 },
209});
210
211const queue = new sqs.Queue(this, 'Queue');
212
213const rule = new events.Rule(this, 'Rule', {
214 schedule: events.Schedule.rate(cdk.Duration.hours(1)),
215});
216
217rule.addTarget(new targets.BatchJob(
218 jobQueue.jobQueueArn,
219 jobQueue,
220 jobDefinition.jobDefinitionArn,
221 jobDefinition, {
222 deadLetterQueue: queue,
223 event: events.RuleTargetInput.fromObject({ SomeParam: 'SomeValue' }),
224 retryAttempts: 2,
225 maxEventAge: cdk.Duration.hours(2),
226 },
227));
228```
229
230## Invoke an API Gateway REST API
231
232Use the `ApiGateway` target to trigger a REST API.
233
234The code snippet below creates a Api Gateway REST API that is invoked every hour.
235
236```ts
237import * as api from '@aws-cdk/aws-apigateway';
238import * as lambda from '@aws-cdk/aws-lambda';
239
240const rule = new events.Rule(this, 'Rule', {
241 schedule: events.Schedule.rate(cdk.Duration.minutes(1)),
242});
243
244const fn = new lambda.Function( this, 'MyFunc', {
245 handler: 'index.handler',
246 runtime: lambda.Runtime.NODEJS_12_X,
247 code: lambda.Code.fromInline( 'exports.handler = e => {}' ),
248} );
249
250const restApi = new api.LambdaRestApi( this, 'MyRestAPI', { handler: fn } );
251
252const dlq = new sqs.Queue(this, 'DeadLetterQueue');
253
254rule.addTarget(
255 new targets.ApiGateway( restApi, {
256 path: '/*/test',
257 method: 'GET',
258 stage: 'prod',
259 pathParameterValues: ['path-value'],
260 headerParameters: {
261 Header1: 'header1',
262 },
263 queryStringParameters: {
264 QueryParam1: 'query-param-1',
265 },
266 deadLetterQueue: dlq
267 } ),
268)
269```
270
271## Invoke an API Destination
272
273Use the `targets.ApiDestination` target to trigger an external API. You need to
274create an `events.Connection` and `events.ApiDestination` as well.
275
276The code snippet below creates an external destination that is invoked every hour.
277
278```ts
279const connection = new events.Connection(this, 'Connection', {
280 authorization: events.Authorization.apiKey('x-api-key', SecretValue.secretsManager('ApiSecretName')),
281 description: 'Connection with API Key x-api-key',
282});
283
284const destination = new events.ApiDestination(this, 'Destination', {
285 connection,
286 endpoint: 'https://example.com',
287 description: 'Calling example.com with API key x-api-key',
288});
289
290const rule = new events.Rule(this, 'Rule', {
291 schedule: events.Schedule.rate(cdk.Duration.minutes(1)),
292 targets: [new targets.ApiDestination(destination)],
293});
294```
295
296## Put an event on an EventBridge bus
297
298Use the `EventBus` target to route event to a different EventBus.
299
300The code snippet below creates the scheduled event rule that route events to an imported event bus.
301
302```ts
303const rule = new events.Rule(this, 'Rule', {
304 schedule: events.Schedule.expression('rate(1 minute)'),
305});
306
307rule.addTarget(new targets.EventBus(
308 events.EventBus.fromEventBusArn(
309 this,
310 'External',
311 `arn:aws:events:eu-west-1:999999999999:event-bus/test-bus`,
312 ),
313));
314```