Event targets for Amazon EventBridge that enable routing events to various AWS services
Targets for AWS system services and infrastructure that can perform administrative tasks and API operations in response to EventBridge events.
Route events to different EventBridge buses for cross-region or cross-account event routing.
/**
* Use an EventBridge bus as a target for Amazon EventBridge rules
*/
class EventBus implements events.IRuleTarget {
constructor(eventBus: events.IEventBus, props?: EventBusProps);
/**
* Returns a RuleTarget that can be used to put events to this EventBridge bus
* as a result from an EventBridge event
*/
bind(rule: events.IRule, id?: string): events.RuleTargetConfig;
}
interface EventBusProps {
/**
* The role to publish the event
* @default a new role will be created
*/
readonly role?: iam.IRole;
/**
* The SQS queue to be used as deadLetterQueue
* Cannot use retryPolicy - retry policy is not supported for EventBridge bus targets
* @default no dead-letter queue
*/
readonly deadLetterQueue?: sqs.IQueue;
}Usage Example:
import * as events from "@aws-cdk/aws-events";
import * as targets from "@aws-cdk/aws-events-targets";
import * as iam from "@aws-cdk/aws-iam";
import * as sqs from "@aws-cdk/aws-sqs";
// Create custom event bus for application events
const applicationBus = new events.EventBus(this, "ApplicationBus", {
eventBusName: "application-events",
});
// Import external event bus (cross-region or cross-account)
const externalBus = events.EventBus.fromEventBusArn(
this,
"ExternalBus",
"arn:aws:events:us-west-2:123456789012:event-bus/partner-events"
);
// Create production event bus
const productionBus = new events.EventBus(this, "ProductionBus", {
eventBusName: "production-events",
});
// Create dead letter queue for failed event routing
const eventRoutingDlq = new sqs.Queue(this, "EventRoutingDLQ", {
queueName: "event-routing-failures",
});
// Create custom role for cross-account event publishing
const crossAccountRole = new iam.Role(this, "CrossAccountEventRole", {
assumedBy: new iam.ServicePrincipal("events.amazonaws.com"),
inlinePolicies: {
EventBridgePublish: new iam.PolicyDocument({
statements: [
new iam.PolicyStatement({
actions: ["events:PutEvents"],
resources: [
externalBus.eventBusArn,
productionBus.eventBusArn,
],
}),
],
}),
},
});
// Rule to route development events to application bus
const devEventsRule = new events.Rule(this, "DevEventsRule", {
eventPattern: {
source: ["myapp.development"],
detailType: [
"Feature Deployed",
"Test Completed",
"Debug Information",
],
},
});
devEventsRule.addTarget(new targets.EventBus(applicationBus, {
deadLetterQueue: eventRoutingDlq,
}));
// Rule to route critical events to production bus
const criticalEventsRule = new events.Rule(this, "CriticalEventsRule", {
eventPattern: {
source: ["myapp"],
detailType: [
"System Failure",
"Security Alert",
"Data Corruption",
],
detail: {
severity: ["CRITICAL", "HIGH"],
},
},
});
criticalEventsRule.addTarget(new targets.EventBus(productionBus, {
role: crossAccountRole,
deadLetterQueue: eventRoutingDlq,
}));
// Rule to forward partner events to external bus
const partnerEventsRule = new events.Rule(this, "PartnerEventsRule", {
eventPattern: {
source: ["myapp.partner"],
detailType: [
"Order Status Update",
"Inventory Change",
"Payment Notification",
],
},
});
partnerEventsRule.addTarget(new targets.EventBus(externalBus, {
role: crossAccountRole,
}));
// Cross-region replication rule
const replicationRule = new events.Rule(this, "ReplicationRule", {
eventPattern: {
source: ["myapp"],
detail: {
replicate: [true],
},
},
});
const backupRegionBus = events.EventBus.fromEventBusArn(
this,
"BackupRegionBus",
"arn:aws:events:us-east-1:123456789012:event-bus/backup-events"
);
replicationRule.addTarget(new targets.EventBus(backupRegionBus));Make direct AWS API calls in response to EventBridge events.
/**
* Make AWS API calls as EventBridge targets
*/
class AwsApi implements events.IRuleTarget {
constructor(props: AwsApiProps);
/**
* Returns a RuleTarget that can be used to make AWS API calls
* as a result from an EventBridge event
*/
bind(rule: events.IRule, id?: string): events.RuleTargetConfig;
}
interface AwsApiInput {
/** AWS service to call (e.g., 'EC2', 'RDS', 'Lambda') */
readonly service: string;
/** Service action to call (e.g., 'DescribeInstances', 'StartDBInstance') */
readonly action: string;
/** Parameters for the service action */
readonly parameters?: any;
/** Regex pattern to catch API errors and continue processing */
readonly catchErrorPattern?: string;
/** API version to use */
readonly apiVersion?: string;
}
interface AwsApiProps extends AwsApiInput {
/** IAM policy statement for the API call */
readonly policyStatement?: iam.PolicyStatement;
}Usage Example:
import * as events from "@aws-cdk/aws-events";
import * as targets from "@aws-cdk/aws-events-targets";
import * as iam from "@aws-cdk/aws-iam";
// Rule for EC2 instance state changes
const ec2StateRule = new events.Rule(this, "EC2StateRule", {
eventPattern: {
source: ["aws.ec2"],
detailType: ["EC2 Instance State-change Notification"],
detail: {
state: ["running"],
},
},
});
// Automatically tag newly launched instances
ec2StateRule.addTarget(new targets.AwsApi({
service: "EC2",
action: "CreateTags",
parameters: {
Resources: [events.EventField.fromPath("$.detail.instance-id")],
Tags: [
{
Key: "AutoTagged",
Value: "true",
},
{
Key: "LaunchTime",
Value: events.EventField.fromPath("$.time"),
},
{
Key: "Account",
Value: events.EventField.fromPath("$.account"),
},
],
},
policyStatement: new iam.PolicyStatement({
actions: ["ec2:CreateTags"],
resources: ["*"],
}),
}));
// Rule for RDS events
const rdsEventsRule = new events.Rule(this, "RDSEventsRule", {
eventPattern: {
source: ["aws.rds"],
detailType: ["RDS DB Instance Event"],
detail: {
EventCategories: ["backup"],
},
},
});
// Create snapshot when backup completes
rdsEventsRule.addTarget(new targets.AwsApi({
service: "RDS",
action: "CreateDBSnapshot",
parameters: {
DBInstanceIdentifier: events.EventField.fromPath("$.detail.SourceId"),
DBSnapshotIdentifier: `automated-snapshot-${events.EventField.fromPath("$.time")}`,
Tags: [
{
Key: "CreatedBy",
Value: "EventBridge",
},
{
Key: "SourceEvent",
Value: events.EventField.fromPath("$.detail.EventCategories[0]"),
},
],
},
policyStatement: new iam.PolicyStatement({
actions: [
"rds:CreateDBSnapshot",
"rds:AddTagsToResource",
],
resources: ["*"],
}),
}));
// Rule for Lambda errors
const lambdaErrorRule = new events.Rule(this, "LambdaErrorRule", {
eventPattern: {
source: ["aws.lambda"],
detailType: ["Lambda Function Invocation Result - Failure"],
},
});
// Update function configuration on repeated failures
lambdaErrorRule.addTarget(new targets.AwsApi({
service: "Lambda",
action: "UpdateFunctionConfiguration",
parameters: {
FunctionName: events.EventField.fromPath("$.detail.requestContext.functionArn"),
Environment: {
Variables: {
LAST_ERROR_TIME: events.EventField.fromPath("$.time"),
ERROR_COUNT: "1", // In real scenario, this would be incremented
},
},
},
catchErrorPattern: "ResourceConflictException", // Ignore concurrent modifications
policyStatement: new iam.PolicyStatement({
actions: ["lambda:UpdateFunctionConfiguration"],
resources: ["*"],
}),
}));
// Rule for S3 bucket events
const s3EventsRule = new events.Rule(this, "S3EventsRule", {
eventPattern: {
source: ["aws.s3"],
detailType: ["Object Created"],
detail: {
bucket: { name: ["sensitive-data-bucket"] },
},
},
});
// Apply encryption to newly uploaded objects
s3EventsRule.addTarget(new targets.AwsApi({
service: "S3",
action: "CopyObject",
parameters: {
Bucket: events.EventField.fromPath("$.detail.bucket.name"),
Key: events.EventField.fromPath("$.detail.object.key"),
CopySource: `${events.EventField.fromPath("$.detail.bucket.name")}/${events.EventField.fromPath("$.detail.object.key")}`,
ServerSideEncryption: "AES256",
MetadataDirective: "REPLACE",
Metadata: {
"encrypted-by": "eventbridge",
"encrypted-at": events.EventField.fromPath("$.time"),
},
},
policyStatement: new iam.PolicyStatement({
actions: [
"s3:GetObject",
"s3:PutObject",
"s3:PutObjectAcl",
],
resources: ["arn:aws:s3:::sensitive-data-bucket/*"],
}),
}));
// Rule for CloudWatch alarms
const alarmRule = new events.Rule(this, "AlarmRule", {
eventPattern: {
source: ["aws.cloudwatch"],
detailType: ["CloudWatch Alarm State Change"],
detail: {
state: { value: ["ALARM"] },
},
},
});
// Scale up Auto Scaling group when alarm triggers
alarmRule.addTarget(new targets.AwsApi({
service: "AutoScaling",
action: "SetDesiredCapacity",
parameters: {
AutoScalingGroupName: "my-asg",
DesiredCapacity: 10,
HonorCooldown: true,
},
policyStatement: new iam.PolicyStatement({
actions: ["autoscaling:SetDesiredCapacity"],
resources: ["*"],
}),
}));
// Rule for Step Functions execution failures
const stepFunctionsRule = new events.Rule(this, "StepFunctionsRule", {
eventPattern: {
source: ["aws.states"],
detailType: ["Step Functions Execution Status Change"],
detail: {
status: ["FAILED"],
},
},
});
// Send notification via SNS when Step Functions fail
stepFunctionsRule.addTarget(new targets.AwsApi({
service: "SNS",
action: "Publish",
parameters: {
TopicArn: "arn:aws:sns:us-east-1:123456789012:step-functions-alerts",
Subject: "Step Functions Execution Failed",
Message: {
executionArn: events.EventField.fromPath("$.detail.executionArn"),
stateMachineArn: events.EventField.fromPath("$.detail.stateMachineArn"),
status: events.EventField.fromPath("$.detail.status"),
cause: events.EventField.fromPath("$.detail.cause"),
timestamp: events.EventField.fromPath("$.time"),
},
},
policyStatement: new iam.PolicyStatement({
actions: ["sns:Publish"],
resources: ["arn:aws:sns:us-east-1:123456789012:step-functions-alerts"],
}),
}));// Automated resource cleanup based on tags
const cleanupRule = new events.Rule(this, "CleanupRule", {
schedule: events.Schedule.cron({
hour: "1",
minute: "0",
}),
});
cleanupRule.addTarget(new targets.AwsApi({
service: "EC2",
action: "DescribeInstances",
parameters: {
Filters: [
{
Name: "tag:Environment",
Values: ["development", "staging"],
},
{
Name: "instance-state-name",
Values: ["running"],
},
],
},
}));// Chain multiple API calls using Step Functions + AwsApi targets
const orchestrationRule = new events.Rule(this, "OrchestrationRule", {
eventPattern: {
source: ["myapp.deployment"],
detailType: ["Deployment Started"],
},
});
// First, update Route 53 health check
orchestrationRule.addTarget(new targets.AwsApi({
service: "Route53",
action: "UpdateHealthCheck",
parameters: {
HealthCheckId: events.EventField.fromPath("$.detail.healthCheckId"),
Disabled: true,
},
}));
// Then scale down Auto Scaling group
orchestrationRule.addTarget(new targets.AwsApi({
service: "AutoScaling",
action: "UpdateAutoScalingGroup",
parameters: {
AutoScalingGroupName: events.EventField.fromPath("$.detail.asgName"),
MinSize: 0,
DesiredCapacity: 0,
},
}));// Replicate configuration across regions
const configReplicationRule = new events.Rule(this, "ConfigReplicationRule", {
eventPattern: {
source: ["aws.ssm"],
detailType: ["Parameter Store Change"],
detail: {
operation: ["Create", "Update"],
name: [{ prefix: "/production/" }],
},
},
});
configReplicationRule.addTarget(new targets.AwsApi({
service: "SSM",
action: "PutParameter",
parameters: {
Name: events.EventField.fromPath("$.detail.name"),
Value: events.EventField.fromPath("$.detail.value"),
Type: events.EventField.fromPath("$.detail.type"),
Overwrite: true,
Tags: [
{
Key: "ReplicatedFrom",
Value: events.EventField.fromPath("$.region"),
},
{
Key: "ReplicatedAt",
Value: events.EventField.fromPath("$.time"),
},
],
},
}));The package includes utility functions for managing permissions and configurations:
/**
* Allow a Lambda function to be called from a rule
*/
function addLambdaPermission(rule: events.IRule, handler: lambda.IFunction): void;
/**
* Allow a rule to send events with failed invocation to an SQS queue
*/
function addToDeadLetterQueueResourcePolicy(rule: events.IRule, queue: sqs.IQueue): void;
/**
* Obtain the Role for the EventBridge event
* Returns existing role if found, creates new one if not
*/
function singletonEventRole(scope: IConstruct): iam.IRole;
/**
* Bind props to base rule target config
*/
function bindBaseTargetConfig(props: TargetBaseProps): object;
/**
* Convert AWS SDK service and action to IAM action format
*/
function awsSdkToIamAction(service: string, action: string): string;
/**
* Check if AWS service exists in the SDK
*/
function checkServiceExists(service: string, handler: lambda.SingletonFunction): void;
/**
* Metadata for AWS SDK services
*/
type AwsSdkMetadata = { [key: string]: any };Install with Tessl CLI
npx tessl i tessl/npm-aws-cdk--aws-events-targets