0
# Compute Targets
1
2
Targets for compute services that can execute code or run workloads in response to EventBridge events.
3
4
## Capabilities
5
6
### Lambda Function Target
7
8
Execute AWS Lambda functions in response to EventBridge events.
9
10
```typescript { .api }
11
/**
12
* Use an AWS Lambda function as an event rule target
13
*/
14
class LambdaFunction implements events.IRuleTarget {
15
constructor(handler: lambda.IFunction, props?: LambdaFunctionProps);
16
17
/**
18
* Returns a RuleTarget that can be used to trigger this Lambda function
19
* as a result from an EventBridge event
20
*/
21
bind(rule: events.IRule, id?: string): events.RuleTargetConfig;
22
}
23
24
interface LambdaFunctionProps extends TargetBaseProps {
25
/**
26
* The event to send to the Lambda function
27
* This will be the payload sent to the Lambda Function
28
* @default the entire EventBridge event
29
*/
30
readonly event?: events.RuleTargetInput;
31
}
32
```
33
34
**Usage Example:**
35
36
```typescript
37
import * as lambda from "@aws-cdk/aws-lambda";
38
import * as events from "@aws-cdk/aws-events";
39
import * as targets from "@aws-cdk/aws-events-targets";
40
import * as sqs from "@aws-cdk/aws-sqs";
41
42
// Create Lambda function
43
const fn = new lambda.Function(this, "MyFunc", {
44
runtime: lambda.Runtime.NODEJS_14_X,
45
handler: "index.handler",
46
code: lambda.Code.fromInline("exports.handler = async (event) => console.log(event)"),
47
});
48
49
// Create rule
50
const rule = new events.Rule(this, "rule", {
51
eventPattern: {
52
source: ["aws.ec2"],
53
},
54
});
55
56
// Create dead letter queue for failed invocations
57
const dlq = new sqs.Queue(this, "DeadLetterQueue");
58
59
// Add Lambda target with error handling
60
rule.addTarget(new targets.LambdaFunction(fn, {
61
deadLetterQueue: dlq,
62
maxEventAge: Duration.hours(2),
63
retryAttempts: 2,
64
event: events.RuleTargetInput.fromObject({
65
timestamp: events.EventField.fromPath("$.time"),
66
source: events.EventField.fromPath("$.source"),
67
}),
68
}));
69
```
70
71
### ECS Task Target
72
73
Run Amazon ECS tasks in response to EventBridge events.
74
75
```typescript { .api }
76
/**
77
* Use Amazon ECS tasks as EventBridge targets
78
*/
79
class EcsTask implements events.IRuleTarget {
80
/** Deprecated security group property */
81
readonly securityGroup?: ec2.ISecurityGroup;
82
/** Security groups for task network interfaces */
83
readonly securityGroups?: ec2.ISecurityGroup[];
84
85
constructor(props: EcsTaskProps);
86
87
/**
88
* Returns a RuleTarget that can be used to run this ECS task
89
* as a result from an EventBridge event
90
*/
91
bind(rule: events.IRule, id?: string): events.RuleTargetConfig;
92
}
93
94
interface EcsTaskProps {
95
/** ECS cluster to run the task on */
96
readonly cluster: ecs.ICluster;
97
/** Task definition to use for the task */
98
readonly taskDefinition: ecs.ITaskDefinition;
99
/** Number of tasks to start */
100
readonly taskCount?: number;
101
/** Container overrides for the task */
102
readonly containerOverrides?: ContainerOverride[];
103
/** Subnet selection for task network interfaces */
104
readonly subnetSelection?: ec2.SubnetSelection;
105
/** Security group for task network interfaces (deprecated) */
106
readonly securityGroup?: ec2.ISecurityGroup;
107
/** Security groups for task network interfaces */
108
readonly securityGroups?: ec2.ISecurityGroup[];
109
/** IAM role to run the ECS task */
110
readonly role?: iam.IRole;
111
/** Platform version for Fargate tasks */
112
readonly platformVersion?: ecs.FargatePlatformVersion;
113
}
114
```
115
116
**Usage Example:**
117
118
```typescript
119
import * as ecs from "@aws-cdk/aws-ecs";
120
import * as ec2 from "@aws-cdk/aws-ec2";
121
import * as events from "@aws-cdk/aws-events";
122
import * as targets from "@aws-cdk/aws-events-targets";
123
124
// Create VPC and cluster
125
const vpc = new ec2.Vpc(this, "VPC");
126
const cluster = new ecs.Cluster(this, "Cluster", { vpc });
127
128
// Create task definition
129
const taskDef = new ecs.FargateTaskDefinition(this, "TaskDef");
130
taskDef.addContainer("container", {
131
image: ecs.ContainerImage.fromRegistry("nginx"),
132
memoryLimitMiB: 256,
133
});
134
135
// Create rule to trigger on S3 object creation
136
const rule = new events.Rule(this, "S3Rule", {
137
eventPattern: {
138
source: ["aws.s3"],
139
detailType: ["Object Created"],
140
},
141
});
142
143
// Add ECS task target with container overrides
144
rule.addTarget(new targets.EcsTask({
145
cluster,
146
taskDefinition: taskDef,
147
taskCount: 1,
148
containerOverrides: [{
149
containerName: "container",
150
environment: [{
151
name: "S3_BUCKET",
152
value: events.EventField.fromPath("$.detail.bucket.name"),
153
}],
154
}],
155
subnetSelection: { subnetType: ec2.SubnetType.PRIVATE },
156
}));
157
```
158
159
### Batch Job Target
160
161
Queue AWS Batch jobs in response to EventBridge events.
162
163
```typescript { .api }
164
/**
165
* Use an AWS Batch Job / Queue as an event rule target
166
*/
167
class BatchJob implements events.IRuleTarget {
168
constructor(
169
/** The JobQueue ARN */
170
jobQueueArn: string,
171
/** The JobQueue Resource */
172
jobQueueScope: IConstruct,
173
/** The jobDefinition ARN */
174
jobDefinitionArn: string,
175
/** The JobDefinition Resource */
176
jobDefinitionScope: IConstruct,
177
props?: BatchJobProps
178
);
179
180
/**
181
* Returns a RuleTarget that can be used to queue this batch job
182
* as a result from an EventBridge event
183
*/
184
bind(rule: events.IRule, id?: string): events.RuleTargetConfig;
185
}
186
187
interface BatchJobProps extends TargetBaseProps {
188
/**
189
* The event to send to the Batch job
190
* This will be the payload sent to the job
191
* @default the entire EventBridge event
192
*/
193
readonly event?: events.RuleTargetInput;
194
195
/**
196
* The size of the array, if this is an array batch job
197
* Valid values are integers between 2 and 10,000
198
* @default no arrayProperties are set
199
*/
200
readonly size?: number;
201
202
/**
203
* The number of times to attempt to retry, if the job fails
204
* Valid values are 1–10
205
* @default no retryStrategy is set
206
*/
207
readonly attempts?: number;
208
209
/**
210
* The name of the submitted job
211
* @default Automatically generated
212
*/
213
readonly jobName?: string;
214
}
215
```
216
217
**Usage Example:**
218
219
```typescript
220
import * as batch from "@aws-cdk/aws-batch";
221
import * as ec2 from "@aws-cdk/aws-ec2";
222
import * as ecs from "@aws-cdk/aws-ecs";
223
import * as events from "@aws-cdk/aws-events";
224
import * as targets from "@aws-cdk/aws-events-targets";
225
import * as sqs from "@aws-cdk/aws-sqs";
226
227
// Create Batch resources
228
const vpc = new ec2.Vpc(this, "VPC");
229
const computeEnvironment = new batch.ComputeEnvironment(this, "ComputeEnv", {
230
managed: false,
231
});
232
233
const jobQueue = new batch.JobQueue(this, "JobQueue", {
234
computeEnvironments: [{
235
computeEnvironment,
236
order: 1,
237
}],
238
});
239
240
const jobDefinition = new batch.JobDefinition(this, "JobDef", {
241
container: {
242
image: ecs.ContainerImage.fromRegistry("busybox"),
243
vcpus: 1,
244
memoryLimitMiB: 512,
245
},
246
});
247
248
// Create rule for scheduled execution
249
const rule = new events.Rule(this, "ScheduledRule", {
250
schedule: events.Schedule.rate(Duration.hours(1)),
251
});
252
253
// Create dead letter queue
254
const dlq = new sqs.Queue(this, "DeadLetterQueue");
255
256
// Add Batch job target
257
rule.addTarget(new targets.BatchJob(
258
jobQueue.jobQueueArn,
259
jobQueue,
260
jobDefinition.jobDefinitionArn,
261
jobDefinition,
262
{
263
deadLetterQueue: dlq,
264
event: events.RuleTargetInput.fromObject({
265
timestamp: events.EventField.fromPath("$.time"),
266
jobData: "scheduled-processing",
267
}),
268
retryAttempts: 2,
269
maxEventAge: Duration.hours(2),
270
jobName: "scheduled-data-processing",
271
}
272
));
273
```
274
275
## Container Override Configuration
276
277
```typescript { .api }
278
interface ContainerOverride {
279
/** Name of the container inside the task definition */
280
readonly containerName: string;
281
/** Command to run inside the container */
282
readonly command?: string[];
283
/** Variables to set in the container's environment */
284
readonly environment?: TaskEnvironmentVariable[];
285
/** The number of cpu units reserved for the container */
286
readonly cpu?: number;
287
/** Hard memory limit on the container */
288
readonly memoryLimit?: number;
289
/** Soft memory limit on the container */
290
readonly memoryReservation?: number;
291
}
292
293
interface TaskEnvironmentVariable {
294
/** Name for the environment variable */
295
readonly name: string;
296
/** Value of the environment variable */
297
readonly value: string;
298
}
299
```