48 types
This library contains integration classes to send Amazon EventBridge to any
number of supported AWS Services. Instances of these classes should be passed
to the rule.addTarget() method.
Currently supported are:
Event Targets for Amazon EventBridge
See the README of the aws-cdk-lib/aws-events library for more information on
EventBridge.
The Codebuild, CodePipeline, Lambda, Kinesis Data Streams, StepFunctions, LogGroup, SQSQueue, SNSTopic and ECSTask targets support attaching a dead letter queue and setting retry policies. See the lambda example. Use escape hatches for the other target types.
Use the LambdaFunction target to invoke a lambda function.
The code snippet below creates an event rule with a Lambda function as a target
triggered for every events from aws.ec2 source. You can optionally attach a
dead letter queue.
require 'aws-cdk-lib'
fn = AWSCDK::Lambda::Function.new(self, "MyFunc", {
runtime: AWSCDK::Lambda::Runtime.NODEJS_LATEST,
handler: "index.handler",
code: AWSCDK::Lambda::Code.from_inline("exports.handler = handler.toString()"),
})
rule = AWSCDK::Events::Rule.new(self, "rule", {
event_pattern: {
source: ["aws.ec2"],
},
})
queue = AWSCDK::SQS::Queue.new(self, "Queue")
rule.add_target(AWSCDK::EventsTargets::LambdaFunction.new(fn, {
dead_letter_queue: queue,
# Optional: add a dead letter queue
max_event_age: AWSCDK::Duration.hours(2),
# Optional: set the maxEventAge retry policy
retry_attempts: 2,
}))
Use the LogGroup target to log your events in a CloudWatch LogGroup.
For example, the following code snippet creates an event rule with a CloudWatch LogGroup as a target.
Every events sent from the aws.ec2 source will be sent to the CloudWatch LogGroup.
require 'aws-cdk-lib'
log_group = AWSCDK::Logs::LogGroup.new(self, "MyLogGroup", {
log_group_name: "MyLogGroup",
})
rule = AWSCDK::Events::Rule.new(self, "rule", {
event_pattern: {
source: ["aws.ec2"],
},
})
rule.add_target(AWSCDK::EventsTargets::CloudWatchLogGroup.new(log_group))
A rule target input can also be specified to modify the event that is sent to the log group. Unlike other event targets, CloudWatchLogs requires a specific input template format.
require 'aws-cdk-lib'
log_group = nil # AWSCDK::Logs::LogGroup
rule = nil # AWSCDK::Events::Rule
rule.add_target(AWSCDK::EventsTargets::CloudWatchLogGroup.new(log_group, {
log_event: AWSCDK::EventsTargets::LogGroupTargetInput.from_object_v2({
timestamp: AWSCDK::Events::EventField.from_path("$.time"),
message: AWSCDK::Events::EventField.from_path("$.detail-type"),
}),
}))
If you want to use static values to overwrite the message make sure that you provide a string
value.
require 'aws-cdk-lib'
log_group = nil # AWSCDK::Logs::LogGroup
rule = nil # AWSCDK::Events::Rule
rule.add_target(AWSCDK::EventsTargets::CloudWatchLogGroup.new(log_group, {
log_event: AWSCDK::EventsTargets::LogGroupTargetInput.from_object_v2({
message: JSON[:stringify]({
CustomField: "CustomValue",
}),
}),
}))
The cloudwatch log event target will create an AWS custom resource internally which will default
to set install_latest_aws_sdk to true. This may be problematic for CN partition deployment. To
workaround this issue, set install_latest_aws_sdk to false.
require 'aws-cdk-lib'
log_group = nil # AWSCDK::Logs::LogGroup
rule = nil # AWSCDK::Events::Rule
rule.add_target(AWSCDK::EventsTargets::CloudWatchLogGroup.new(log_group, {
install_latest_aws_sdk: false,
}))
Use the CodeBuildProject target to trigger a CodeBuild project.
The code snippet below creates a CodeCommit repository that triggers a CodeBuild project on commit to the master branch. You can optionally attach a dead letter queue.
require 'aws-cdk-lib'
repo = AWSCDK::Codecommit::Repository.new(self, "MyRepo", {
repository_name: "aws-cdk-codebuild-events",
})
project = AWSCDK::CodeBuild::Project.new(self, "MyProject", {
source: AWSCDK::CodeBuild::Source.code_commit({repository: repo}),
})
dead_letter_queue = AWSCDK::SQS::Queue.new(self, "DeadLetterQueue")
# trigger a build when a commit is pushed to the repo
on_commit_rule = repo.on_commit("OnCommit", {
target: AWSCDK::EventsTargets::CodeBuildProject.new(project, {
dead_letter_queue: dead_letter_queue,
}),
branches: ["master"],
})
Use the CodePipeline target to trigger a CodePipeline pipeline.
The code snippet below creates a CodePipeline pipeline that is triggered every hour
require 'aws-cdk-lib'
pipeline = AWSCDK::Codepipeline::Pipeline.new(self, "Pipeline")
rule = AWSCDK::Events::Rule.new(self, "Rule", {
schedule: AWSCDK::Events::Schedule.expression("rate(1 hour)"),
})
rule.add_target(AWSCDK::EventsTargets::CodePipeline.new(pipeline))
Use the SfnStateMachine target to trigger a State Machine.
The code snippet below creates a Simple StateMachine that is triggered every minute with a dummy object as input. You can optionally attach a dead letter queue to the target.
require 'aws-cdk-lib'
rule = AWSCDK::Events::Rule.new(self, "Rule", {
schedule: AWSCDK::Events::Schedule.rate(AWSCDK::Duration.minutes(1)),
})
dlq = AWSCDK::SQS::Queue.new(self, "DeadLetterQueue")
role = AWSCDK::IAM::Role.new(self, "Role", {
assumed_by: AWSCDK::IAM::ServicePrincipal.new("events.amazonaws.com"),
})
state_machine = AWSCDK::StepFunctions::StateMachine.new(self, "SM", {
definition: AWSCDK::StepFunctions::Wait.new(self, "Hello", {time: AWSCDK::StepFunctions::WaitTime.duration(AWSCDK::Duration.seconds(10))}),
})
rule.add_target(AWSCDK::EventsTargets::SfnStateMachine.new(state_machine, {
input: AWSCDK::Events::RuleTargetInput.from_object({SomeParam: "SomeValue"}),
dead_letter_queue: dlq,
role: role,
}))
Use the BatchJob target to queue a Batch job.
The code snippet below creates a Simple JobQueue that is triggered every hour with a dummy object as input. You can optionally attach a dead letter queue to the target.
require 'aws-cdk-lib'
vpc = nil # AWSCDK::EC2::VPC
compute_environment = AWSCDK::Batch::FargateComputeEnvironment.new(self, "ComputeEnv", {
vpc: vpc,
})
job_queue = AWSCDK::Batch::JobQueue.new(self, "JobQueue", {
priority: 1,
compute_environments: [
{
compute_environment: compute_environment,
order: 1,
},
],
})
job_definition = AWSCDK::Batch::ECSJobDefinition.new(self, "MyJob", {
container: AWSCDK::Batch::ECSEC2ContainerDefinition.new(self, "Container", {
image: AWSCDK::ECS::ContainerImage.from_registry("test-repo"),
memory: AWSCDK::Size.mebibytes(2048),
cpu: 256,
}),
})
queue = AWSCDK::SQS::Queue.new(self, "Queue")
rule = AWSCDK::Events::Rule.new(self, "Rule", {
schedule: AWSCDK::Events::Schedule.rate(AWSCDK::Duration.hours(1)),
})
rule.add_target(AWSCDK::EventsTargets::BatchJob.new(job_queue.job_queue_arn, job_queue, job_definition.job_definition_arn, job_definition, {
dead_letter_queue: queue,
event: AWSCDK::Events::RuleTargetInput.from_object({SomeParam: "SomeValue"}),
retry_attempts: 2,
max_event_age: AWSCDK::Duration.hours(2),
}))
Use the ApiGateway target to trigger a REST API.
The code snippet below creates a Api Gateway REST API that is invoked every hour.
require 'aws-cdk-lib'
rule = AWSCDK::Events::Rule.new(self, "Rule", {
schedule: AWSCDK::Events::Schedule.rate(AWSCDK::Duration.minutes(1)),
})
fn = AWSCDK::Lambda::Function.new(self, "MyFunc", {
handler: "index.handler",
runtime: AWSCDK::Lambda::Runtime.NODEJS_LATEST,
code: AWSCDK::Lambda::Code.from_inline("exports.handler = e => {}"),
})
rest_api = AWSCDK::APIGateway::LambdaRestAPI.new(self, "MyRestAPI", {handler: fn})
dlq = AWSCDK::SQS::Queue.new(self, "DeadLetterQueue")
rule.add_target(
AWSCDK::EventsTargets::APIGateway.new(rest_api, {
path: "/*/test",
method: "GET",
stage: "prod",
path_parameter_values: ["path-value"],
header_parameters: {
Header1: "header1",
},
query_string_parameters: {
QueryParam1: "query-param-1",
},
dead_letter_queue: dlq,
}))
Use the ApiGatewayV2 target to trigger a HTTP API.
require 'aws-cdk-lib'
http_api = nil # AWSCDK::APIGatewayv2::HttpAPI
rule = nil # AWSCDK::Events::Rule
rule.add_target(AWSCDK::EventsTargets::APIGatewayV2.new(http_api))
Use the AwsApi target to make direct AWS API calls from EventBridge rules. This is useful for invoking AWS services that don't have a dedicated EventBridge target.
The following example shows how to update an ECS service when a rule is triggered:
rule = AWSCDK::Events::Rule.new(self, "Rule", {
schedule: AWSCDK::Events::Schedule.rate(AWSCDK::Duration.hours(1)),
})
rule.add_target(AWSCDK::EventsTargets::AWSAPI.new({
service: "ECS",
action: "updateService",
parameters: {
service: "my-service",
force_new_deployment: true,
},
}))
By default, the AwsApi target automatically creates the necessary IAM permissions based on the service and action you specify. The permission format follows the pattern: service:Action.
For example:
ECS service with update_service action โ ecs:UpdateService permissionRDS service with create_db_snapshot action โ rds:CreateDBSnapshot permissionIn some cases, you may need to provide a custom IAM policy statement, especially when:
*)require 'aws-cdk-lib'
rule = nil # AWSCDK::Events::Rule
bucket = nil # AWSCDK::S3::Bucket
rule.add_target(AWSCDK::EventsTargets::AWSAPI.new({
service: "s3",
action: "GetBucketEncryption",
parameters: {
Bucket: bucket.bucket_name,
},
policy_statement: AWSCDK::IAM::PolicyStatement.new({
effect: AWSCDK::IAM::Effect::ALLOW,
actions: ["s3:GetEncryptionConfiguration"],
resources: [bucket.bucket_arn],
}),
}))
Use the targets.ApiDestination target to trigger an external API. You need to
create an events.Connection and events.ApiDestination as well.
The code snippet below creates an external destination that is invoked every hour.
connection = AWSCDK::Events::Connection.new(self, "Connection", {
authorization: AWSCDK::Events::Authorization.api_key("x-api-key", AWSCDK::SecretValue.secrets_manager("ApiSecretName")),
description: "Connection with API Key x-api-key",
})
destination = AWSCDK::Events::APIDestination.new(self, "Destination", {
connection: connection,
endpoint: "https://example.com",
description: "Calling example.com with API key x-api-key",
})
rule = AWSCDK::Events::Rule.new(self, "Rule", {
schedule: AWSCDK::Events::Schedule.rate(AWSCDK::Duration.minutes(1)),
targets: [AWSCDK::EventsTargets::APIDestination.new(destination)],
})
You can also import an existing connection and destination to create additional rules:
connection = AWSCDK::Events::Connection.from_event_bus_arn(self, "Connection", "arn:aws:events:us-east-1:123456789012:event-bus/EventBusName", "arn:aws:secretsmanager:us-east-1:123456789012:secret:SecretName-f3gDy9")
api_destination_arn = "arn:aws:events:us-east-1:123456789012:api-destination/DestinationName/11111111-1111-1111-1111-111111111111"
api_destination_arn_for_policy = "arn:aws:events:us-east-1:123456789012:api-destination/DestinationName"
destination = AWSCDK::Events::APIDestination.from_api_destination_attributes(self, "Destination", {
api_destination_arn: api_destination_arn,
connection: connection,
api_destination_arn_for_policy: api_destination_arn_for_policy,
})
rule = AWSCDK::Events::Rule.new(self, "OtherRule", {
schedule: AWSCDK::Events::Schedule.rate(AWSCDK::Duration.minutes(10)),
targets: [AWSCDK::EventsTargets::APIDestination.new(destination)],
})
Use the AppSync target to trigger an AppSync GraphQL API. You need to
create an AppSync.GraphqlApi configured with AWS_IAM authorization mode.
The code snippet below creates an AppSync GraphQL API target that is invoked every hour, calling the publish mutation.
require 'aws-cdk-lib'
api = AWSCDK::AppSync::GraphqlAPI.new(self, "api", {
name: "api",
definition: AWSCDK::AppSync::Definition.from_file("schema.graphql"),
authorization_config: {
default_authorization: {authorization_type: AWSCDK::AppSync::AuthorizationType::IAM},
},
})
rule = AWSCDK::Events::Rule.new(self, "Rule", {
schedule: AWSCDK::Events::Schedule.rate(AWSCDK::Duration.hours(1)),
})
rule.add_target(AWSCDK::EventsTargets::AppSync.new(api, {
graph_ql_operation: "mutation Publish($message: String!){ publish(message: $message) { message } }",
variables: AWSCDK::Events::RuleTargetInput.from_object({
message: "hello world",
}),
}))
You can pass an existing role with the proper permissions to be used for the target when the rule is triggered. The code snippet below uses an existing role and grants permissions to use the publish Mutation on the GraphQL API.
require 'aws-cdk-lib'
api = AWSCDK::AppSync::GraphqlAPI.from_graphql_api_attributes(self, "ImportedAPI", {
graphql_api_id: "<api-id>",
graphql_api_arn: "<api-arn>",
graph_ql_endpoint_arn: "<api-endpoint-arn>",
visibility: AWSCDK::AppSync::Visibility::GLOBAL,
modes: [AWSCDK::AppSync::AuthorizationType::IAM],
})
rule = AWSCDK::Events::Rule.new(self, "Rule", {schedule: AWSCDK::Events::Schedule.rate(AWSCDK::Duration.minutes(1))})
role = AWSCDK::IAM::Role.new(self, "Role", {assumed_by: AWSCDK::IAM::ServicePrincipal.new("events.amazonaws.com")})
# allow EventBridge to use the `publish` mutation
api.grant_mutation(role, "publish")
rule.add_target(AWSCDK::EventsTargets::AppSync.new(api, {
graph_ql_operation: "mutation Publish($message: String!){ publish(message: $message) { message } }",
variables: AWSCDK::Events::RuleTargetInput.from_object({
message: "hello world",
}),
event_role: role,
}))
Use the EventBus target to route event to a different EventBus.
The code snippet below creates the scheduled event rule that route events to an imported event bus.
rule = AWSCDK::Events::Rule.new(self, "Rule", {
schedule: AWSCDK::Events::Schedule.expression("rate(1 minute)"),
})
rule.add_target(AWSCDK::EventsTargets::EventBus.new(AWSCDK::Events::EventBus.from_event_bus_arn(self, "External", "arn:aws:events:eu-west-1:999999999999:event-bus/test-bus")))
Use the FirehoseDeliveryStream target to put event to an Amazon Data Firehose delivery stream.
The code snippet below creates the scheduled event rule that put events to an Amazon Data Firehose delivery stream.
require 'aws-cdk-lib'
bucket = nil # AWSCDK::S3::Bucket
stream = AWSCDK::KinesisFirehose::DeliveryStream.new(self, "DeliveryStream", {
destination: AWSCDK::KinesisFirehose::S3Bucket.new(bucket),
})
rule = AWSCDK::Events::Rule.new(self, "Rule", {
schedule: AWSCDK::Events::Schedule.expression("rate(1 minute)"),
})
rule.add_target(AWSCDK::EventsTargets::FirehoseDeliveryStream.new(stream))
Use the EcsTask target to run an ECS Task.
The code snippet below creates a scheduled event rule that will run the task described in task_definition every hour.
By default, ECS tasks run from EventBridge targets will not have tags applied to
them. You can set the propagate_tags field to propagate the tags set on the task
definition to the task initialized by the event trigger.
If you want to set tags independent of those applied to the TaskDefinition, you
can use the tags array. Both of these fields can be used together or separately
to set tags on the triggered task.
require 'aws-cdk-lib'
cluster = nil # AWSCDK::ECS::ICluster
task_definition = nil # AWSCDK::ECS::TaskDefinition
rule = AWSCDK::Events::Rule.new(self, "Rule", {
schedule: AWSCDK::Events::Schedule.rate(AWSCDK::Duration.hours(1)),
})
rule.add_target(
AWSCDK::EventsTargets::ECSTask.new({
cluster: cluster,
task_definition: task_definition,
propagate_tags: AWSCDK::ECS::PropagatedTagSource::TASK_DEFINITION,
tags: [
{
key: "my-tag",
value: "my-tag-value",
},
],
}))
By default, if is_ec2_compatible for the task_definition is true, the EC2 type is used as
the launch type for the task, otherwise the FARGATE type.
If you want to override the default launch type, you can set the launch_type property.
require 'aws-cdk-lib'
cluster = nil # AWSCDK::ECS::ICluster
task_definition = nil # AWSCDK::ECS::TaskDefinition
rule = AWSCDK::Events::Rule.new(self, "Rule", {
schedule: AWSCDK::Events::Schedule.rate(AWSCDK::Duration.hours(1)),
})
rule.add_target(AWSCDK::EventsTargets::ECSTask.new({
cluster: cluster,
task_definition: task_definition,
launch_type: AWSCDK::ECS::LaunchType::FARGATE,
}))
You can set the assign_public_ip flag to assign public IP addresses to tasks.
If you want to detach the public IP address from the task, you have to set the flag false.
You can specify the flag true only when the launch type is set to FARGATE.
require 'aws-cdk-lib'
cluster = nil # AWSCDK::ECS::ICluster
task_definition = nil # AWSCDK::ECS::TaskDefinition
rule = AWSCDK::Events::Rule.new(self, "Rule", {
schedule: AWSCDK::Events::Schedule.rate(AWSCDK::Duration.hours(1)),
})
rule.add_target(
AWSCDK::EventsTargets::ECSTask.new({
cluster: cluster,
task_definition: task_definition,
assign_public_ip: true,
subnet_selection: {subnet_type: AWSCDK::EC2::SubnetType::PUBLIC},
}))
If you use Amazon ECS Exec, you can run commands in or get a shell to a container running on an Amazon EC2 instance or on AWS Fargate.
require 'aws-cdk-lib'
cluster = nil # AWSCDK::ECS::ICluster
task_definition = nil # AWSCDK::ECS::TaskDefinition
rule = AWSCDK::Events::Rule.new(self, "Rule", {
schedule: AWSCDK::Events::Schedule.rate(AWSCDK::Duration.hours(1)),
})
rule.add_target(AWSCDK::EventsTargets::ECSTask.new({
cluster: cluster,
task_definition: task_definition,
task_count: 1,
container_overrides: [
{
container_name: "TheContainer",
command: ["echo", AWSCDK::Events::EventField.from_path("$.detail.event")],
},
],
enable_execute_command: true,
}))
You can override values in the task definition by setting the corresponding properties in the EcsTaskProps. All
values in the TaskOverrides API are
supported.
require 'aws-cdk-lib'
cluster = nil # AWSCDK::ECS::ICluster
task_definition = nil # AWSCDK::ECS::TaskDefinition
rule = AWSCDK::Events::Rule.new(self, "Rule", {
schedule: AWSCDK::Events::Schedule.rate(AWSCDK::Duration.hours(1)),
})
rule.add_target(AWSCDK::EventsTargets::ECSTask.new({
cluster: cluster,
task_definition: task_definition,
task_count: 1,
# Overrides the cpu and memory values in the task definition
cpu: "512",
memory: "512",
}))
Use the RedshiftQuery target to schedule an Amazon Redshift Query.
The code snippet below creates the scheduled event rule that route events to an Amazon Redshift Query
require 'aws-cdk-lib'
workgroup = nil # AWSCDK::RedshiftServerless::CfnWorkgroup
rule = AWSCDK::Events::Rule.new(self, "Rule", {
schedule: AWSCDK::Events::Schedule.rate(AWSCDK::Duration.hours(1)),
})
dlq = AWSCDK::SQS::Queue.new(self, "DeadLetterQueue")
rule.add_target(AWSCDK::EventsTargets::RedshiftQuery.new(workgroup.attr_workgroup_workgroup_arn, {
database: "dev",
dead_letter_queue: dlq,
sql: ["SELECT * FROM foo", "SELECT * FROM baz"],
}))
Use the SqsQueue target to send events to an SQS queue.
The code snippet below creates an event rule that sends events to an SQS queue every hour:
queue = AWSCDK::SQS::Queue.new(self, "MyQueue")
rule = AWSCDK::Events::Rule.new(self, "Rule", {
schedule: AWSCDK::Events::Schedule.rate(AWSCDK::Duration.hours(1)),
})
rule.add_target(AWSCDK::EventsTargets::SQSQueue.new(queue))
You can specify a message_group_id to ensure messages are processed in order. This parameter is required for FIFO queues and optional for standard queues:
# FIFO queue - messageGroupId required
fifo_queue = AWSCDK::SQS::Queue.new(self, "MyFifoQueue", {
fifo: true,
})
fifo_rule = AWSCDK::Events::Rule.new(self, "FifoRule", {
schedule: AWSCDK::Events::Schedule.rate(AWSCDK::Duration.hours(1)),
})
fifo_rule.add_target(AWSCDK::EventsTargets::SQSQueue.new(fifo_queue, {
message_group_id: "MyMessageGroupId",
}))
# Standard queue - messageGroupId optional (SQS Fair queue feature)
standard_queue = AWSCDK::SQS::Queue.new(self, "MyStandardQueue")
standard_rule = AWSCDK::Events::Rule.new(self, "StandardRule", {
schedule: AWSCDK::Events::Schedule.rate(AWSCDK::Duration.hours(1)),
})
standard_rule.add_target(AWSCDK::EventsTargets::SQSQueue.new(standard_queue, {
message_group_id: "MyMessageGroupId",
}))
Use the SnsTopic target to publish to an SNS Topic.
The code snippet below creates the scheduled event rule that publishes to an SNS Topic using a resource policy.
require 'aws-cdk-lib'
topic = nil # AWSCDK::SNS::ITopic
rule = AWSCDK::Events::Rule.new(self, "Rule", {
schedule: AWSCDK::Events::Schedule.rate(AWSCDK::Duration.hours(1)),
})
rule.add_target(AWSCDK::EventsTargets::SNSTopic.new(topic))
Alternatively, a role can be attached to the target when the rule is triggered.
require 'aws-cdk-lib'
topic = nil # AWSCDK::SNS::ITopic
rule = AWSCDK::Events::Rule.new(self, "Rule", {
schedule: AWSCDK::Events::Schedule.rate(AWSCDK::Duration.hours(1)),
})
rule.add_target(AWSCDK::EventsTargets::SNSTopic.new(topic, {authorize_using_role: true}))