0
# System Targets
1
2
Targets for AWS system services and infrastructure that can perform administrative tasks and API operations in response to EventBridge events.
3
4
## Capabilities
5
6
### EventBridge Bus Target
7
8
Route events to different EventBridge buses for cross-region or cross-account event routing.
9
10
```typescript { .api }
11
/**
12
* Use an EventBridge bus as a target for Amazon EventBridge rules
13
*/
14
class EventBus implements events.IRuleTarget {
15
constructor(eventBus: events.IEventBus, props?: EventBusProps);
16
17
/**
18
* Returns a RuleTarget that can be used to put events to this EventBridge bus
19
* as a result from an EventBridge event
20
*/
21
bind(rule: events.IRule, id?: string): events.RuleTargetConfig;
22
}
23
24
interface EventBusProps {
25
/**
26
* The role to publish the event
27
* @default a new role will be created
28
*/
29
readonly role?: iam.IRole;
30
31
/**
32
* The SQS queue to be used as deadLetterQueue
33
* Cannot use retryPolicy - retry policy is not supported for EventBridge bus targets
34
* @default no dead-letter queue
35
*/
36
readonly deadLetterQueue?: sqs.IQueue;
37
}
38
```
39
40
**Usage Example:**
41
42
```typescript
43
import * as events from "@aws-cdk/aws-events";
44
import * as targets from "@aws-cdk/aws-events-targets";
45
import * as iam from "@aws-cdk/aws-iam";
46
import * as sqs from "@aws-cdk/aws-sqs";
47
48
// Create custom event bus for application events
49
const applicationBus = new events.EventBus(this, "ApplicationBus", {
50
eventBusName: "application-events",
51
});
52
53
// Import external event bus (cross-region or cross-account)
54
const externalBus = events.EventBus.fromEventBusArn(
55
this,
56
"ExternalBus",
57
"arn:aws:events:us-west-2:123456789012:event-bus/partner-events"
58
);
59
60
// Create production event bus
61
const productionBus = new events.EventBus(this, "ProductionBus", {
62
eventBusName: "production-events",
63
});
64
65
// Create dead letter queue for failed event routing
66
const eventRoutingDlq = new sqs.Queue(this, "EventRoutingDLQ", {
67
queueName: "event-routing-failures",
68
});
69
70
// Create custom role for cross-account event publishing
71
const crossAccountRole = new iam.Role(this, "CrossAccountEventRole", {
72
assumedBy: new iam.ServicePrincipal("events.amazonaws.com"),
73
inlinePolicies: {
74
EventBridgePublish: new iam.PolicyDocument({
75
statements: [
76
new iam.PolicyStatement({
77
actions: ["events:PutEvents"],
78
resources: [
79
externalBus.eventBusArn,
80
productionBus.eventBusArn,
81
],
82
}),
83
],
84
}),
85
},
86
});
87
88
// Rule to route development events to application bus
89
const devEventsRule = new events.Rule(this, "DevEventsRule", {
90
eventPattern: {
91
source: ["myapp.development"],
92
detailType: [
93
"Feature Deployed",
94
"Test Completed",
95
"Debug Information",
96
],
97
},
98
});
99
100
devEventsRule.addTarget(new targets.EventBus(applicationBus, {
101
deadLetterQueue: eventRoutingDlq,
102
}));
103
104
// Rule to route critical events to production bus
105
const criticalEventsRule = new events.Rule(this, "CriticalEventsRule", {
106
eventPattern: {
107
source: ["myapp"],
108
detailType: [
109
"System Failure",
110
"Security Alert",
111
"Data Corruption",
112
],
113
detail: {
114
severity: ["CRITICAL", "HIGH"],
115
},
116
},
117
});
118
119
criticalEventsRule.addTarget(new targets.EventBus(productionBus, {
120
role: crossAccountRole,
121
deadLetterQueue: eventRoutingDlq,
122
}));
123
124
// Rule to forward partner events to external bus
125
const partnerEventsRule = new events.Rule(this, "PartnerEventsRule", {
126
eventPattern: {
127
source: ["myapp.partner"],
128
detailType: [
129
"Order Status Update",
130
"Inventory Change",
131
"Payment Notification",
132
],
133
},
134
});
135
136
partnerEventsRule.addTarget(new targets.EventBus(externalBus, {
137
role: crossAccountRole,
138
}));
139
140
// Cross-region replication rule
141
const replicationRule = new events.Rule(this, "ReplicationRule", {
142
eventPattern: {
143
source: ["myapp"],
144
detail: {
145
replicate: [true],
146
},
147
},
148
});
149
150
const backupRegionBus = events.EventBus.fromEventBusArn(
151
this,
152
"BackupRegionBus",
153
"arn:aws:events:us-east-1:123456789012:event-bus/backup-events"
154
);
155
156
replicationRule.addTarget(new targets.EventBus(backupRegionBus));
157
```
158
159
### AWS API Target
160
161
Make direct AWS API calls in response to EventBridge events.
162
163
```typescript { .api }
164
/**
165
* Make AWS API calls as EventBridge targets
166
*/
167
class AwsApi implements events.IRuleTarget {
168
constructor(props: AwsApiProps);
169
170
/**
171
* Returns a RuleTarget that can be used to make AWS API calls
172
* as a result from an EventBridge event
173
*/
174
bind(rule: events.IRule, id?: string): events.RuleTargetConfig;
175
}
176
177
interface AwsApiInput {
178
/** AWS service to call (e.g., 'EC2', 'RDS', 'Lambda') */
179
readonly service: string;
180
/** Service action to call (e.g., 'DescribeInstances', 'StartDBInstance') */
181
readonly action: string;
182
/** Parameters for the service action */
183
readonly parameters?: any;
184
/** Regex pattern to catch API errors and continue processing */
185
readonly catchErrorPattern?: string;
186
/** API version to use */
187
readonly apiVersion?: string;
188
}
189
190
interface AwsApiProps extends AwsApiInput {
191
/** IAM policy statement for the API call */
192
readonly policyStatement?: iam.PolicyStatement;
193
}
194
```
195
196
**Usage Example:**
197
198
```typescript
199
import * as events from "@aws-cdk/aws-events";
200
import * as targets from "@aws-cdk/aws-events-targets";
201
import * as iam from "@aws-cdk/aws-iam";
202
203
// Rule for EC2 instance state changes
204
const ec2StateRule = new events.Rule(this, "EC2StateRule", {
205
eventPattern: {
206
source: ["aws.ec2"],
207
detailType: ["EC2 Instance State-change Notification"],
208
detail: {
209
state: ["running"],
210
},
211
},
212
});
213
214
// Automatically tag newly launched instances
215
ec2StateRule.addTarget(new targets.AwsApi({
216
service: "EC2",
217
action: "CreateTags",
218
parameters: {
219
Resources: [events.EventField.fromPath("$.detail.instance-id")],
220
Tags: [
221
{
222
Key: "AutoTagged",
223
Value: "true",
224
},
225
{
226
Key: "LaunchTime",
227
Value: events.EventField.fromPath("$.time"),
228
},
229
{
230
Key: "Account",
231
Value: events.EventField.fromPath("$.account"),
232
},
233
],
234
},
235
policyStatement: new iam.PolicyStatement({
236
actions: ["ec2:CreateTags"],
237
resources: ["*"],
238
}),
239
}));
240
241
// Rule for RDS events
242
const rdsEventsRule = new events.Rule(this, "RDSEventsRule", {
243
eventPattern: {
244
source: ["aws.rds"],
245
detailType: ["RDS DB Instance Event"],
246
detail: {
247
EventCategories: ["backup"],
248
},
249
},
250
});
251
252
// Create snapshot when backup completes
253
rdsEventsRule.addTarget(new targets.AwsApi({
254
service: "RDS",
255
action: "CreateDBSnapshot",
256
parameters: {
257
DBInstanceIdentifier: events.EventField.fromPath("$.detail.SourceId"),
258
DBSnapshotIdentifier: `automated-snapshot-${events.EventField.fromPath("$.time")}`,
259
Tags: [
260
{
261
Key: "CreatedBy",
262
Value: "EventBridge",
263
},
264
{
265
Key: "SourceEvent",
266
Value: events.EventField.fromPath("$.detail.EventCategories[0]"),
267
},
268
],
269
},
270
policyStatement: new iam.PolicyStatement({
271
actions: [
272
"rds:CreateDBSnapshot",
273
"rds:AddTagsToResource",
274
],
275
resources: ["*"],
276
}),
277
}));
278
279
// Rule for Lambda errors
280
const lambdaErrorRule = new events.Rule(this, "LambdaErrorRule", {
281
eventPattern: {
282
source: ["aws.lambda"],
283
detailType: ["Lambda Function Invocation Result - Failure"],
284
},
285
});
286
287
// Update function configuration on repeated failures
288
lambdaErrorRule.addTarget(new targets.AwsApi({
289
service: "Lambda",
290
action: "UpdateFunctionConfiguration",
291
parameters: {
292
FunctionName: events.EventField.fromPath("$.detail.requestContext.functionArn"),
293
Environment: {
294
Variables: {
295
LAST_ERROR_TIME: events.EventField.fromPath("$.time"),
296
ERROR_COUNT: "1", // In real scenario, this would be incremented
297
},
298
},
299
},
300
catchErrorPattern: "ResourceConflictException", // Ignore concurrent modifications
301
policyStatement: new iam.PolicyStatement({
302
actions: ["lambda:UpdateFunctionConfiguration"],
303
resources: ["*"],
304
}),
305
}));
306
307
// Rule for S3 bucket events
308
const s3EventsRule = new events.Rule(this, "S3EventsRule", {
309
eventPattern: {
310
source: ["aws.s3"],
311
detailType: ["Object Created"],
312
detail: {
313
bucket: { name: ["sensitive-data-bucket"] },
314
},
315
},
316
});
317
318
// Apply encryption to newly uploaded objects
319
s3EventsRule.addTarget(new targets.AwsApi({
320
service: "S3",
321
action: "CopyObject",
322
parameters: {
323
Bucket: events.EventField.fromPath("$.detail.bucket.name"),
324
Key: events.EventField.fromPath("$.detail.object.key"),
325
CopySource: `${events.EventField.fromPath("$.detail.bucket.name")}/${events.EventField.fromPath("$.detail.object.key")}`,
326
ServerSideEncryption: "AES256",
327
MetadataDirective: "REPLACE",
328
Metadata: {
329
"encrypted-by": "eventbridge",
330
"encrypted-at": events.EventField.fromPath("$.time"),
331
},
332
},
333
policyStatement: new iam.PolicyStatement({
334
actions: [
335
"s3:GetObject",
336
"s3:PutObject",
337
"s3:PutObjectAcl",
338
],
339
resources: ["arn:aws:s3:::sensitive-data-bucket/*"],
340
}),
341
}));
342
343
// Rule for CloudWatch alarms
344
const alarmRule = new events.Rule(this, "AlarmRule", {
345
eventPattern: {
346
source: ["aws.cloudwatch"],
347
detailType: ["CloudWatch Alarm State Change"],
348
detail: {
349
state: { value: ["ALARM"] },
350
},
351
},
352
});
353
354
// Scale up Auto Scaling group when alarm triggers
355
alarmRule.addTarget(new targets.AwsApi({
356
service: "AutoScaling",
357
action: "SetDesiredCapacity",
358
parameters: {
359
AutoScalingGroupName: "my-asg",
360
DesiredCapacity: 10,
361
HonorCooldown: true,
362
},
363
policyStatement: new iam.PolicyStatement({
364
actions: ["autoscaling:SetDesiredCapacity"],
365
resources: ["*"],
366
}),
367
}));
368
369
// Rule for Step Functions execution failures
370
const stepFunctionsRule = new events.Rule(this, "StepFunctionsRule", {
371
eventPattern: {
372
source: ["aws.states"],
373
detailType: ["Step Functions Execution Status Change"],
374
detail: {
375
status: ["FAILED"],
376
},
377
},
378
});
379
380
// Send notification via SNS when Step Functions fail
381
stepFunctionsRule.addTarget(new targets.AwsApi({
382
service: "SNS",
383
action: "Publish",
384
parameters: {
385
TopicArn: "arn:aws:sns:us-east-1:123456789012:step-functions-alerts",
386
Subject: "Step Functions Execution Failed",
387
Message: {
388
executionArn: events.EventField.fromPath("$.detail.executionArn"),
389
stateMachineArn: events.EventField.fromPath("$.detail.stateMachineArn"),
390
status: events.EventField.fromPath("$.detail.status"),
391
cause: events.EventField.fromPath("$.detail.cause"),
392
timestamp: events.EventField.fromPath("$.time"),
393
},
394
},
395
policyStatement: new iam.PolicyStatement({
396
actions: ["sns:Publish"],
397
resources: ["arn:aws:sns:us-east-1:123456789012:step-functions-alerts"],
398
}),
399
}));
400
```
401
402
## System Integration Patterns
403
404
### Resource Management Automation
405
406
```typescript
407
// Automated resource cleanup based on tags
408
const cleanupRule = new events.Rule(this, "CleanupRule", {
409
schedule: events.Schedule.cron({
410
hour: "1",
411
minute: "0",
412
}),
413
});
414
415
cleanupRule.addTarget(new targets.AwsApi({
416
service: "EC2",
417
action: "DescribeInstances",
418
parameters: {
419
Filters: [
420
{
421
Name: "tag:Environment",
422
Values: ["development", "staging"],
423
},
424
{
425
Name: "instance-state-name",
426
Values: ["running"],
427
},
428
],
429
},
430
}));
431
```
432
433
### Multi-Service Orchestration
434
435
```typescript
436
// Chain multiple API calls using Step Functions + AwsApi targets
437
const orchestrationRule = new events.Rule(this, "OrchestrationRule", {
438
eventPattern: {
439
source: ["myapp.deployment"],
440
detailType: ["Deployment Started"],
441
},
442
});
443
444
// First, update Route 53 health check
445
orchestrationRule.addTarget(new targets.AwsApi({
446
service: "Route53",
447
action: "UpdateHealthCheck",
448
parameters: {
449
HealthCheckId: events.EventField.fromPath("$.detail.healthCheckId"),
450
Disabled: true,
451
},
452
}));
453
454
// Then scale down Auto Scaling group
455
orchestrationRule.addTarget(new targets.AwsApi({
456
service: "AutoScaling",
457
action: "UpdateAutoScalingGroup",
458
parameters: {
459
AutoScalingGroupName: events.EventField.fromPath("$.detail.asgName"),
460
MinSize: 0,
461
DesiredCapacity: 0,
462
},
463
}));
464
```
465
466
### Cross-Region Operations
467
468
```typescript
469
// Replicate configuration across regions
470
const configReplicationRule = new events.Rule(this, "ConfigReplicationRule", {
471
eventPattern: {
472
source: ["aws.ssm"],
473
detailType: ["Parameter Store Change"],
474
detail: {
475
operation: ["Create", "Update"],
476
name: [{ prefix: "/production/" }],
477
},
478
},
479
});
480
481
configReplicationRule.addTarget(new targets.AwsApi({
482
service: "SSM",
483
action: "PutParameter",
484
parameters: {
485
Name: events.EventField.fromPath("$.detail.name"),
486
Value: events.EventField.fromPath("$.detail.value"),
487
Type: events.EventField.fromPath("$.detail.type"),
488
Overwrite: true,
489
Tags: [
490
{
491
Key: "ReplicatedFrom",
492
Value: events.EventField.fromPath("$.region"),
493
},
494
{
495
Key: "ReplicatedAt",
496
Value: events.EventField.fromPath("$.time"),
497
},
498
],
499
},
500
}));
501
```
502
503
## Utility Functions
504
505
The package includes utility functions for managing permissions and configurations:
506
507
```typescript { .api }
508
/**
509
* Allow a Lambda function to be called from a rule
510
*/
511
function addLambdaPermission(rule: events.IRule, handler: lambda.IFunction): void;
512
513
/**
514
* Allow a rule to send events with failed invocation to an SQS queue
515
*/
516
function addToDeadLetterQueueResourcePolicy(rule: events.IRule, queue: sqs.IQueue): void;
517
518
/**
519
* Obtain the Role for the EventBridge event
520
* Returns existing role if found, creates new one if not
521
*/
522
function singletonEventRole(scope: IConstruct): iam.IRole;
523
524
/**
525
* Bind props to base rule target config
526
*/
527
function bindBaseTargetConfig(props: TargetBaseProps): object;
528
529
/**
530
* Convert AWS SDK service and action to IAM action format
531
*/
532
function awsSdkToIamAction(service: string, action: string): string;
533
534
/**
535
* Check if AWS service exists in the SDK
536
*/
537
function checkServiceExists(service: string, handler: lambda.SingletonFunction): void;
538
539
/**
540
* Metadata for AWS SDK services
541
*/
542
type AwsSdkMetadata = { [key: string]: any };
543
```