Package: aws-cdk.aws-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 theMigrating to AWS CDK v2guide.This library contains integration classes to send Amazon EventBridge to any
number of supported AWS Services. Instances of these classes should be passed
to therule.addTarget()method.Currently supported are:Start a CodeBuild buildStart a CodePipeline pipelineRun an ECS taskInvoke a Lambda functionInvoke a API Gateway REST APIPublish a message to an SNS topicSend a message to an SQS queueStart a StepFunctions state machineQueue a Batch jobMake an AWS API callPut a record to a Kinesis streamLog an event into a LogGroupPut a record to a Kinesis Data Firehose streamPut an event on an EventBridge busSend an event to EventBridge API DestinationSee the README of the@aws-cdk/aws-eventslibrary for more information on
EventBridge.Event retry policy and using dead-letter queuesThe Codebuild, CodePipeline, Lambda, StepFunctions, LogGroup and SQSQueue targets support attaching adead letter queue and setting retry policies. See thelambda example.
Useescape hatchesfor the other target types.Invoke a Lambda functionUse theLambdaFunctiontarget to invoke a lambda function.The code snippet below creates an event rule with a Lambda function as a target
triggered for every events fromaws.ec2source. You can optionally attach adead letter queue.importaws_cdk.aws_lambdaaslambda_fn=lambda_.Function(self,"MyFunc",runtime=lambda_.Runtime.NODEJS_14_X,handler="index.handler",code=lambda_.Code.from_inline("exports.handler = handler.toString()"))rule=events.Rule(self,"rule",event_pattern=events.EventPattern(source=["aws.ec2"]))queue=sqs.Queue(self,"Queue")rule.add_target(targets.LambdaFunction(fn,dead_letter_queue=queue,# Optional: add a dead letter queuemax_event_age=cdk.Duration.hours(2),# Optional: set the maxEventAge retry policyretry_attempts=2))Log an event into a LogGroupUse theLogGrouptarget 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 theaws.ec2source will be sent to the CloudWatch LogGroup.importaws_cdk.aws_logsaslogslog_group=logs.LogGroup(self,"MyLogGroup",log_group_name="MyLogGroup")rule=events.Rule(self,"rule",event_pattern=events.EventPattern(source=["aws.ec2"]))rule.add_target(targets.CloudWatchLogGroup(log_group))Start a CodeBuild buildUse theCodeBuildProjecttarget 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 adead letter queue.importaws_cdk.aws_codebuildascodebuildimportaws_cdk.aws_codecommitascodecommitrepo=codecommit.Repository(self,"MyRepo",repository_name="aws-cdk-codebuild-events")project=codebuild.Project(self,"MyProject",source=codebuild.Source.code_commit(repository=repo))dead_letter_queue=sqs.Queue(self,"DeadLetterQueue")# trigger a build when a commit is pushed to the repoon_commit_rule=repo.on_commit("OnCommit",target=targets.CodeBuildProject(project,dead_letter_queue=dead_letter_queue),branches=["master"])Start a CodePipeline pipelineUse theCodePipelinetarget to trigger a CodePipeline pipeline.The code snippet below creates a CodePipeline pipeline that is triggered every hourimportaws_cdk.aws_codepipelineascodepipelinepipeline=codepipeline.Pipeline(self,"Pipeline")rule=events.Rule(self,"Rule",schedule=events.Schedule.expression("rate(1 hour)"))rule.add_target(targets.CodePipeline(pipeline))Start a StepFunctions state machineUse theSfnStateMachinetarget 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 adead letter queueto the target.importaws_cdk.aws_iamasiamimportaws_cdk.aws_stepfunctionsassfnrule=events.Rule(self,"Rule",schedule=events.Schedule.rate(cdk.Duration.minutes(1)))dlq=sqs.Queue(self,"DeadLetterQueue")role=iam.Role(self,"Role",assumed_by=iam.ServicePrincipal("events.amazonaws.com"))state_machine=sfn.StateMachine(self,"SM",definition=sfn.Wait(self,"Hello",time=sfn.WaitTime.duration(cdk.Duration.seconds(10))))rule.add_target(targets.SfnStateMachine(state_machine,input=events.RuleTargetInput.from_object({"SomeParam":"SomeValue"}),dead_letter_queue=dlq,role=role))Queue a Batch jobUse theBatchJobtarget 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 adead letter queueto the target.importaws_cdk.aws_batchasbatchfromaws_cdk.aws_ecsimportContainerImagejob_queue=batch.JobQueue(self,"MyQueue",compute_environments=[batch.JobQueueComputeEnvironment(compute_environment=batch.ComputeEnvironment(self,"ComputeEnvironment",managed=False),order=1)])job_definition=batch.JobDefinition(self,"MyJob",container=batch.JobDefinitionContainer(image=ContainerImage.from_registry("test-repo")))queue=sqs.Queue(self,"Queue")rule=events.Rule(self,"Rule",schedule=events.Schedule.rate(cdk.Duration.hours(1)))rule.add_target(targets.BatchJob(job_queue.job_queue_arn,job_queue,job_definition.job_definition_arn,job_definition,dead_letter_queue=queue,event=events.RuleTargetInput.from_object({"SomeParam":"SomeValue"}),retry_attempts=2,max_event_age=cdk.Duration.hours(2)))Invoke an API Gateway REST APIUse theApiGatewaytarget to trigger a REST API.The code snippet below creates a Api Gateway REST API that is invoked every hour.importaws_cdk.aws_apigatewayasapiimportaws_cdk.aws_lambdaaslambda_rule=events.Rule(self,"Rule",schedule=events.Schedule.rate(cdk.Duration.minutes(1)))fn=lambda_.Function(self,"MyFunc",handler="index.handler",runtime=lambda_.Runtime.NODEJS_14_X,code=lambda_.Code.from_inline("exports.handler = e =>{}"))rest_api=api.LambdaRestApi(self,"MyRestAPI",handler=fn)dlq=sqs.Queue(self,"DeadLetterQueue")rule.add_target(targets.ApiGateway(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))Invoke an API DestinationUse thetargets.ApiDestinationtarget to trigger an external API. You need to
create anevents.Connectionandevents.ApiDestinationas well.The code snippet below creates an external destination that is invoked every hour.connection=events.Connection(self,"Connection",authorization=events.Authorization.api_key("x-api-key",SecretValue.secrets_manager("ApiSecretName")),description="Connection with API Key x-api-key")destination=events.ApiDestination(self,"Destination",connection=connection,endpoint="https://example.com",description="Calling example.com with API key x-api-key")rule=events.Rule(self,"Rule",schedule=events.Schedule.rate(cdk.Duration.minutes(1)),targets=[targets.ApiDestination(destination)])Put an event on an EventBridge busUse theEventBustarget 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=events.Rule(self,"Rule",schedule=events.Schedule.expression("rate(1 minute)"))rule.add_target(targets.EventBus(events.EventBus.from_event_bus_arn(self,"External","arn:aws:events:eu-west-1:999999999999:event-bus/test-bus")))