1 | # Event Targets for Amazon EventBridge
|
2 |
|
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 |
|
11 |
|
12 | This library contains integration classes to send Amazon EventBridge to any
|
13 | number of supported AWS Services. Instances of these classes should be passed
|
14 | to the `rule.addTarget()` method.
|
15 |
|
16 | Currently 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 |
|
34 | See the README of the `@aws-cdk/aws-events` library for more information on
|
35 | EventBridge.
|
36 |
|
37 | ## Event retry policy and using dead-letter queues
|
38 |
|
39 | The 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).
|
40 | Use [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 |
|
44 | Use the `LambdaFunction` target to invoke a lambda function.
|
45 |
|
46 | The code snippet below creates an event rule with a Lambda function as a target
|
47 | triggered 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
|
51 | import * as lambda from '@aws-cdk/aws-lambda';
|
52 |
|
53 | const 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 |
|
59 | const rule = new events.Rule(this, 'rule', {
|
60 | eventPattern: {
|
61 | source: ["aws.ec2"],
|
62 | },
|
63 | });
|
64 |
|
65 | const queue = new sqs.Queue(this, 'Queue');
|
66 |
|
67 | rule.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 |
|
76 | Use the `LogGroup` target to log your events in a CloudWatch LogGroup.
|
77 |
|
78 | For example, the following code snippet creates an event rule with a CloudWatch LogGroup as a target.
|
79 | Every events sent from the `aws.ec2` source will be sent to the CloudWatch LogGroup.
|
80 |
|
81 | ```ts
|
82 | import * as logs from '@aws-cdk/aws-logs';
|
83 |
|
84 | const logGroup = new logs.LogGroup(this, 'MyLogGroup', {
|
85 | logGroupName: 'MyLogGroup',
|
86 | });
|
87 |
|
88 | const rule = new events.Rule(this, 'rule', {
|
89 | eventPattern: {
|
90 | source: ["aws.ec2"],
|
91 | },
|
92 | });
|
93 |
|
94 | rule.addTarget(new targets.CloudWatchLogGroup(logGroup));
|
95 | ```
|
96 |
|
97 | ## Start a CodeBuild build
|
98 |
|
99 | Use the `CodeBuildProject` target to trigger a CodeBuild project.
|
100 |
|
101 | The code snippet below creates a CodeCommit repository that triggers a CodeBuild project
|
102 | on 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
|
106 | import * as codebuild from '@aws-cdk/aws-codebuild';
|
107 | import * as codecommit from '@aws-cdk/aws-codecommit';
|
108 |
|
109 | const repo = new codecommit.Repository(this, 'MyRepo', {
|
110 | repositoryName: 'aws-cdk-codebuild-events',
|
111 | });
|
112 |
|
113 | const project = new codebuild.Project(this, 'MyProject', {
|
114 | source: codebuild.Source.codeCommit({ repository: repo }),
|
115 | });
|
116 |
|
117 | const deadLetterQueue = new sqs.Queue(this, 'DeadLetterQueue');
|
118 |
|
119 | // trigger a build when a commit is pushed to the repo
|
120 | const 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 |
|
130 | Use the `CodePipeline` target to trigger a CodePipeline pipeline.
|
131 |
|
132 | The code snippet below creates a CodePipeline pipeline that is triggered every hour
|
133 |
|
134 | ```ts
|
135 | import * as codepipeline from '@aws-cdk/aws-codepipeline';
|
136 |
|
137 | const pipeline = new codepipeline.Pipeline(this, 'Pipeline');
|
138 |
|
139 | const rule = new events.Rule(this, 'Rule', {
|
140 | schedule: events.Schedule.expression('rate(1 hour)'),
|
141 | });
|
142 |
|
143 | rule.addTarget(new targets.CodePipeline(pipeline));
|
144 | ```
|
145 |
|
146 | ## Start a StepFunctions state machine
|
147 |
|
148 | Use the `SfnStateMachine` target to trigger a State Machine.
|
149 |
|
150 | The code snippet below creates a Simple StateMachine that is triggered every minute with a
|
151 | dummy object as input.
|
152 | You can optionally attach a
|
153 | [dead letter queue](https://docs.aws.amazon.com/eventbridge/latest/userguide/rule-dlq.html)
|
154 | to the target.
|
155 |
|
156 | ```ts
|
157 | import * as iam from '@aws-cdk/aws-iam';
|
158 | import * as sfn from '@aws-cdk/aws-stepfunctions';
|
159 |
|
160 | const rule = new events.Rule(this, 'Rule', {
|
161 | schedule: events.Schedule.rate(cdk.Duration.minutes(1)),
|
162 | });
|
163 |
|
164 | const dlq = new sqs.Queue(this, 'DeadLetterQueue');
|
165 |
|
166 | const role = new iam.Role(this, 'Role', {
|
167 | assumedBy: new iam.ServicePrincipal('events.amazonaws.com'),
|
168 | });
|
169 | const stateMachine = new sfn.StateMachine(this, 'SM', {
|
170 | definition: new sfn.Wait(this, 'Hello', { time: sfn.WaitTime.duration(cdk.Duration.seconds(10)) })
|
171 | });
|
172 |
|
173 | rule.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 |
|
182 | Use the `BatchJob` target to queue a Batch job.
|
183 |
|
184 | The code snippet below creates a Simple JobQueue that is triggered every hour with a
|
185 | dummy object as input.
|
186 | You can optionally attach a
|
187 | [dead letter queue](https://docs.aws.amazon.com/eventbridge/latest/userguide/rule-dlq.html)
|
188 | to the target.
|
189 |
|
190 | ```ts
|
191 | import * as batch from '@aws-cdk/aws-batch';
|
192 | import { ContainerImage } from '@aws-cdk/aws-ecs';
|
193 |
|
194 | const 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 |
|
205 | const jobDefinition = new batch.JobDefinition(this, 'MyJob', {
|
206 | container: {
|
207 | image: ContainerImage.fromRegistry('test-repo'),
|
208 | },
|
209 | });
|
210 |
|
211 | const queue = new sqs.Queue(this, 'Queue');
|
212 |
|
213 | const rule = new events.Rule(this, 'Rule', {
|
214 | schedule: events.Schedule.rate(cdk.Duration.hours(1)),
|
215 | });
|
216 |
|
217 | rule.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 |
|
232 | Use the `ApiGateway` target to trigger a REST API.
|
233 |
|
234 | The code snippet below creates a Api Gateway REST API that is invoked every hour.
|
235 |
|
236 | ```ts
|
237 | import * as api from '@aws-cdk/aws-apigateway';
|
238 | import * as lambda from '@aws-cdk/aws-lambda';
|
239 |
|
240 | const rule = new events.Rule(this, 'Rule', {
|
241 | schedule: events.Schedule.rate(cdk.Duration.minutes(1)),
|
242 | });
|
243 |
|
244 | const 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 |
|
250 | const restApi = new api.LambdaRestApi( this, 'MyRestAPI', { handler: fn } );
|
251 |
|
252 | const dlq = new sqs.Queue(this, 'DeadLetterQueue');
|
253 |
|
254 | rule.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 |
|
273 | Use the `targets.ApiDestination` target to trigger an external API. You need to
|
274 | create an `events.Connection` and `events.ApiDestination` as well.
|
275 |
|
276 | The code snippet below creates an external destination that is invoked every hour.
|
277 |
|
278 | ```ts
|
279 | const 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 |
|
284 | const 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 |
|
290 | const 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 |
|
298 | Use the `EventBus` target to route event to a different EventBus.
|
299 |
|
300 | The code snippet below creates the scheduled event rule that route events to an imported event bus.
|
301 |
|
302 | ```ts
|
303 | const rule = new events.Rule(this, 'Rule', {
|
304 | schedule: events.Schedule.expression('rate(1 minute)'),
|
305 | });
|
306 |
|
307 | rule.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 | ```
|