Package: aws-cdk.aws-events
Amazon EventBridge Construct Library---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.Amazon EventBridge delivers a near real-time stream of system events that
describe changes in AWS resources. For example, an AWS CodePipeline emits theState
Changeevent when the pipeline changes its state.Events: An event indicates a change in your AWS environment. AWS resources
can generate events when their state changes. For example, Amazon EC2
generates an event when the state of an EC2 instance changes from pending to
running, and Amazon EC2 Auto Scaling generates events when it launches or
terminates instances. AWS CloudTrail publishes events when you make API calls.
You can generate custom application-level events and publish them to
EventBridge. You can also set up scheduled events that are generated on
a periodic basis. For a list of services that generate events, and sample
events from each service, seeEventBridge Event Examples From Each
Supported
Service.Targets: A target processes events. Targets can include Amazon EC2
instances, AWS Lambda functions, Kinesis streams, Amazon ECS tasks, Step
Functions state machines, Amazon SNS topics, Amazon SQS queues, Amazon CloudWatch LogGroups, and built-in
targets. A target receives events in JSON format.Rules: A rule matches incoming events and routes them to targets for
processing. A single rule can route to multiple targets, all of which are
processed in parallel. Rules are not processed in a particular order. This
enables different parts of an organization to look for and process the events
that are of interest to them. A rule can customize the JSON sent to the
target, by passing only certain parts or by overwriting it with a constant.EventBuses: An event bus can receive events from your own custom applications
or it can receive events from applications and services created by AWS SaaS partners.
SeeCreating an Event Bus.RuleTheRuleconstruct defines an EventBridge rule which monitors an
event based on anevent
patternand invokeevent targetswhen the pattern is matched against a triggered
event. Event targets are objects that implement theIRuleTargetinterface.Normally, you will use one of thesource.onXxx(name[, target[, options]]) -> Rulemethods on the event source to define an event rule associated with
the specific activity. You can targets either via props, or add targets usingrule.addTarget.For example, to define an rule that triggers a CodeBuild project build when a
commit is pushed to the "master" branch of a CodeCommit repository:# repo: codecommit.Repository# project: codebuild.Projecton_commit_rule=repo.on_commit("OnCommit",target=targets.CodeBuildProject(project),branches=["master"])You can add additional targets, with optionalinput
transformerusingeventRule.addTarget(target[, input]). For example, we can add a SNS
topic target which formats a human-readable message for the commit.For example, this adds an SNS topic as a target:# on_commit_rule: events.Rule# topic: sns.Topicon_commit_rule.add_target(targets.SnsTopic(topic,message=events.RuleTargetInput.from_text(f"A commit was pushed to the repository{codecommit.ReferenceEvent.repositoryName}on branch{codecommit.ReferenceEvent.referenceName}")))Or using an Object:# on_commit_rule: events.Rule# topic: sns.Topicon_commit_rule.add_target(targets.SnsTopic(topic,message=events.RuleTargetInput.from_object({"DataType":f"custom_{events.EventField.fromPath('$.detail-type')}"})))SchedulingYou can configure a Rule to run on a schedule (cron or rate).
Rate must be specified in minutes, hours or days.The following example runs a task every day at 4am:fromaws_cdk.aws_eventsimportRule,Schedulefromaws_cdk.aws_events_targetsimportEcsTaskfromaws_cdk.aws_ecsimportCluster,TaskDefinitionfromaws_cdk.aws_iamimportRole# cluster: Cluster# task_definition: TaskDefinition# role: Roleecs_task_target=EcsTask(cluster=cluster,task_definition=task_definition,role=role)Rule(self,"ScheduleRule",schedule=Schedule.cron(minute="0",hour="4"),targets=[ecs_task_target])If you want to specify Fargate platform version, setplatformVersionin EcsTask's props like the following example:# cluster: ecs.Cluster# task_definition: ecs.TaskDefinition# role: iam.Roleplatform_version=ecs.FargatePlatformVersion.VERSION1_4ecs_task_target=targets.EcsTask(cluster=cluster,task_definition=task_definition,role=role,platform_version=platform_version)Event TargetsThe@aws-cdk/aws-events-targetsmodule includes classes that implement theIRuleTargetinterface for various AWS services.The following targets are supported:targets.CodeBuildProject: Start an AWS CodeBuild buildtargets.CodePipeline: Start an AWS CodePipeline pipeline executiontargets.EcsTask: Start a task on an Amazon ECS clustertargets.LambdaFunction: Invoke an AWS Lambda functiontargets.SnsTopic: Publish into an SNS topictargets.SqsQueue: Send a message to an Amazon SQS Queuetargets.SfnStateMachine: Trigger an AWS Step Functions state machinetargets.BatchJob: Queue an AWS Batch Jobtargets.AwsApi: Make an AWS API calltargets.ApiGateway: Invoke an AWS API Gatewaytargets.ApiDestination: Make an call to an external destinationCross-account and cross-region targetsIt's possible to have the source of the event and a target in separate AWS accounts and regions:fromaws_cdk.coreimportEnvironment,Environmentfromaws_cdk.coreimportApp,Stackimportaws_cdk.aws_codebuildascodebuildimportaws_cdk.aws_codecommitascodecommitimportaws_cdk.aws_events_targetsastargetsapp=App()account1="11111111111"account2="22222222222"stack1=Stack(app,"Stack1",env=Environment(account=account1,region="us-west-1"))repo=codecommit.Repository(stack1,"Repository",repository_name="myrepository")stack2=Stack(app,"Stack2",env=Environment(account=account2,region="us-east-1"))project=codebuild.Project(stack2,"Project")repo.on_commit("OnCommit",target=targets.CodeBuildProject(project))In this situation, the CDK will wire the 2 accounts together:It will generate a rule in the source stack with the event bus of the target account as the targetIt will generate a rule in the target stack, with the provided targetIt will generate a separate stack that gives the source account permissions to publish events
to the event bus of the target account in the given region,
and make sure its deployed before the source stackFor more information, see theAWS documentation on cross-account events.ArchivingIt is possible to archive all or some events sent to an event bus. It is then possible toreplay these events.bus=events.EventBus(self,"bus",event_bus_name="MyCustomEventBus")bus.archive("MyArchive",archive_name="MyCustomEventBusArchive",description="MyCustomerEventBus Archive",event_pattern=events.EventPattern(account=[Stack.of(self).account]),retention=Duration.days(365))Granting PutEvents to an existing EventBusTo import an existing EventBus into your CDK application, useEventBus.fromEventBusArn,EventBus.fromEventBusAttributesorEventBus.fromEventBusNamefactory method.Then, you can use thegrantPutEventsTomethod to grantevent:PutEventsto the eventBus.# lambda_function: lambda.Functionevent_bus=events.EventBus.from_event_bus_arn(self,"ImportedEventBus","arn:aws:events:us-east-1:111111111:event-bus/my-event-bus")# now you can just call methods on the eventbusevent_bus.grant_put_events_to(lambda_function)