Package software.amazon.awscdk.services.events.targets
Event Targets for Amazon EventBridge
---
AWS CDK v1 has reached End-of-Support on 2023-06-01. This package is no longer being updated, and users should migrate to AWS CDK v2.
For more information on how to migrate, see the Migrating to AWS CDK v2 guide.
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:
- Start a CodeBuild build
- Start a CodePipeline pipeline
- Run an ECS task
- Invoke a Lambda function
- Invoke a API Gateway REST API
- Publish a message to an SNS topic
- Send a message to an SQS queue
- Start a StepFunctions state machine
- Queue a Batch job
- Make an AWS API call
- Put a record to a Kinesis stream
- Log an event into a LogGroup
- Put a record to a Kinesis Data Firehose stream
- Put an event on an EventBridge bus
- Send an event to EventBridge API Destination
See the README of the @aws-cdk/aws-events library for more information on
EventBridge.
Event retry policy and using dead-letter queues
The Codebuild, CodePipeline, Lambda, StepFunctions, LogGroup and SQSQueue targets support attaching a dead letter queue and setting retry policies. See the lambda example. Use escape hatches for the other target types.
Invoke a Lambda function
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.
import software.amazon.awscdk.services.lambda.*;
Function fn = Function.Builder.create(this, "MyFunc")
.runtime(Runtime.NODEJS_14_X)
.handler("index.handler")
.code(Code.fromInline("exports.handler = handler.toString()"))
.build();
Rule rule = Rule.Builder.create(this, "rule")
.eventPattern(EventPattern.builder()
.source(List.of("aws.ec2"))
.build())
.build();
Queue queue = new Queue(this, "Queue");
rule.addTarget(LambdaFunction.Builder.create(fn)
.deadLetterQueue(queue) // Optional: add a dead letter queue
.maxEventAge(Duration.hours(2)) // Optional: set the maxEventAge retry policy
.retryAttempts(2)
.build());
Log an event into a LogGroup
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.
import software.amazon.awscdk.services.logs.*;
LogGroup logGroup = LogGroup.Builder.create(this, "MyLogGroup")
.logGroupName("MyLogGroup")
.build();
Rule rule = Rule.Builder.create(this, "rule")
.eventPattern(EventPattern.builder()
.source(List.of("aws.ec2"))
.build())
.build();
rule.addTarget(new CloudWatchLogGroup(logGroup));
Start a CodeBuild build
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.
import software.amazon.awscdk.services.codebuild.*;
import software.amazon.awscdk.services.codecommit.*;
Repository repo = Repository.Builder.create(this, "MyRepo")
.repositoryName("aws-cdk-codebuild-events")
.build();
Project project = Project.Builder.create(this, "MyProject")
.source(Source.codeCommit(CodeCommitSourceProps.builder().repository(repo).build()))
.build();
Queue deadLetterQueue = new Queue(this, "DeadLetterQueue");
// trigger a build when a commit is pushed to the repo
Rule onCommitRule = repo.onCommit("OnCommit", OnCommitOptions.builder()
.target(CodeBuildProject.Builder.create(project)
.deadLetterQueue(deadLetterQueue)
.build())
.branches(List.of("master"))
.build());
Start a CodePipeline pipeline
Use the CodePipeline target to trigger a CodePipeline pipeline.
The code snippet below creates a CodePipeline pipeline that is triggered every hour
import software.amazon.awscdk.services.codepipeline.*;
Pipeline pipeline = new Pipeline(this, "Pipeline");
Rule rule = Rule.Builder.create(this, "Rule")
.schedule(Schedule.expression("rate(1 hour)"))
.build();
rule.addTarget(new CodePipeline(pipeline));
Start a StepFunctions state machine
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.
import software.amazon.awscdk.services.iam.*;
import software.amazon.awscdk.services.stepfunctions.*;
Rule rule = Rule.Builder.create(this, "Rule")
.schedule(Schedule.rate(Duration.minutes(1)))
.build();
Queue dlq = new Queue(this, "DeadLetterQueue");
Role role = Role.Builder.create(this, "Role")
.assumedBy(new ServicePrincipal("events.amazonaws.com"))
.build();
StateMachine stateMachine = StateMachine.Builder.create(this, "SM")
.definition(Wait.Builder.create(this, "Hello").time(WaitTime.duration(Duration.seconds(10))).build())
.build();
rule.addTarget(SfnStateMachine.Builder.create(stateMachine)
.input(RuleTargetInput.fromObject(Map.of("SomeParam", "SomeValue")))
.deadLetterQueue(dlq)
.role(role)
.build());
Queue a Batch job
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.
import software.amazon.awscdk.services.batch.*;
import software.amazon.awscdk.services.ecs.ContainerImage;
JobQueue jobQueue = JobQueue.Builder.create(this, "MyQueue")
.computeEnvironments(List.of(JobQueueComputeEnvironment.builder()
.computeEnvironment(ComputeEnvironment.Builder.create(this, "ComputeEnvironment")
.managed(false)
.build())
.order(1)
.build()))
.build();
JobDefinition jobDefinition = JobDefinition.Builder.create(this, "MyJob")
.container(JobDefinitionContainer.builder()
.image(ContainerImage.fromRegistry("test-repo"))
.build())
.build();
Queue queue = new Queue(this, "Queue");
Rule rule = Rule.Builder.create(this, "Rule")
.schedule(Schedule.rate(Duration.hours(1)))
.build();
rule.addTarget(BatchJob.Builder.create(jobQueue.getJobQueueArn(), jobQueue, jobDefinition.getJobDefinitionArn(), jobDefinition)
.deadLetterQueue(queue)
.event(RuleTargetInput.fromObject(Map.of("SomeParam", "SomeValue")))
.retryAttempts(2)
.maxEventAge(Duration.hours(2))
.build());
Invoke an API Gateway REST API
Use the ApiGateway target to trigger a REST API.
The code snippet below creates a Api Gateway REST API that is invoked every hour.
import software.amazon.awscdk.services.apigateway.*;
import software.amazon.awscdk.services.lambda.*;
Rule rule = Rule.Builder.create(this, "Rule")
.schedule(Schedule.rate(Duration.minutes(1)))
.build();
Function fn = Function.Builder.create(this, "MyFunc")
.handler("index.handler")
.runtime(Runtime.NODEJS_14_X)
.code(Code.fromInline("exports.handler = e => {}"))
.build();
LambdaRestApi restApi = LambdaRestApi.Builder.create(this, "MyRestAPI").handler(fn).build();
Queue dlq = new Queue(this, "DeadLetterQueue");
rule.addTarget(
ApiGateway.Builder.create(restApi)
.path("/*/test")
.method("GET")
.stage("prod")
.pathParameterValues(List.of("path-value"))
.headerParameters(Map.of(
"Header1", "header1"))
.queryStringParameters(Map.of(
"QueryParam1", "query-param-1"))
.deadLetterQueue(dlq)
.build());
Invoke an API Destination
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 connection = Connection.Builder.create(this, "Connection")
.authorization(Authorization.apiKey("x-api-key", SecretValue.secretsManager("ApiSecretName")))
.description("Connection with API Key x-api-key")
.build();
ApiDestination destination = ApiDestination.Builder.create(this, "Destination")
.connection(connection)
.endpoint("https://example.com")
.description("Calling example.com with API key x-api-key")
.build();
Rule rule = Rule.Builder.create(this, "Rule")
.schedule(Schedule.rate(Duration.minutes(1)))
.targets(List.of(new ApiDestination(destination)))
.build();
Put an event on an EventBridge bus
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 rule = Rule.Builder.create(this, "Rule")
.schedule(Schedule.expression("rate(1 minute)"))
.build();
rule.addTarget(new EventBus(EventBus.fromEventBusArn(this, "External", "arn:aws:events:eu-west-1:999999999999:event-bus/test-bus")));
Deprecated: AWS CDK v1 has reached End-of-Support on 2023-06-01.
This package is no longer being updated, and users should migrate to AWS CDK v2.
For more information on how to migrate, see https://docs.aws.amazon.com/cdk/v2/guide/migrating-v2.html-
ClassDescriptionUse an API Destination rule target.A fluent builder for
ApiDestination.Customize the EventBridge Api Destinations Target.A builder forApiDestinationPropsAn implementation forApiDestinationPropsUse an API Gateway REST APIs as a target for Amazon EventBridge rules.A fluent builder forApiGateway.Customize the API Gateway Event Target.A builder forApiGatewayPropsAn implementation forApiGatewayPropsUse an AWS Lambda function that makes API calls as an event rule target.A fluent builder forAwsApi.Rule target input for an AwsApi target.A builder forAwsApiInputAn implementation forAwsApiInputProperties for an AwsApi target.A builder forAwsApiPropsAn implementation forAwsApiPropsUse an AWS Batch Job / Queue as an event rule target.A fluent builder forBatchJob.Customize the Batch Job Event Target.A builder forBatchJobPropsAn implementation forBatchJobPropsUse an AWS CloudWatch LogGroup as an event rule target.A fluent builder forCloudWatchLogGroup.Start a CodeBuild build when an Amazon EventBridge rule is triggered.A fluent builder forCodeBuildProject.Customize the CodeBuild Event Target.A builder forCodeBuildProjectPropsAn implementation forCodeBuildProjectPropsAllows the pipeline to be used as an EventBridge rule target.A fluent builder forCodePipeline.Customization options when creating aCodePipelineevent target.A builder forCodePipelineTargetOptionsAn implementation forCodePipelineTargetOptionsExample:A builder forContainerOverrideAn implementation forContainerOverrideStart a task on an ECS cluster.A fluent builder forEcsTask.Properties to define an ECS Event Task.A builder forEcsTaskPropsAn implementation forEcsTaskPropsNotify an existing Event Bus of an event.A fluent builder forEventBus.Configuration properties of an Event Bus event.A builder forEventBusPropsAn implementation forEventBusPropsCustomize the Firehose Stream Event Target.A fluent builder forKinesisFirehoseStream.Customize the Firehose Stream Event Target.A builder forKinesisFirehoseStreamPropsAn implementation forKinesisFirehoseStreamPropsUse a Kinesis Stream as a target for AWS CloudWatch event rules.A fluent builder forKinesisStream.Customize the Kinesis Stream Event Target.A builder forKinesisStreamPropsAn implementation forKinesisStreamPropsUse an AWS Lambda function as an event rule target.A fluent builder forLambdaFunction.Customize the Lambda Event Target.A builder forLambdaFunctionPropsAn implementation forLambdaFunctionPropsCustomize the CloudWatch LogGroup Event Target.A builder forLogGroupPropsAn implementation forLogGroupPropsUse a StepFunctions state machine as a target for Amazon EventBridge rules.A fluent builder forSfnStateMachine.Customize the Step Functions State Machine target.A builder forSfnStateMachinePropsAn implementation forSfnStateMachinePropsUse an SNS topic as a target for Amazon EventBridge rules.A fluent builder forSnsTopic.Customize the SNS Topic Event Target.A builder forSnsTopicPropsAn implementation forSnsTopicPropsUse an SQS Queue as a target for Amazon EventBridge rules.A fluent builder forSqsQueue.Customize the SQS Queue Event Target.A builder forSqsQueuePropsAn implementation forSqsQueuePropsThe generic properties for an RuleTarget.A builder forTargetBasePropsAn implementation forTargetBasePropsAn environment variable to be set in the container run as a task.A builder forTaskEnvironmentVariableAn implementation forTaskEnvironmentVariable