Package software.amazon.awscdk.services.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 the Migrating to AWS CDK v2 guide.
Amazon EventBridge delivers a near real-time stream of system events that describe changes in AWS resources. For example, an AWS CodePipeline emits the State Change event 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, see EventBridge 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. See Creating an Event Bus.
Rule
The Rule
construct defines an EventBridge rule which monitors an
event based on an event
pattern
and invoke event targets when the pattern is matched against a triggered
event. Event targets are objects that implement the IRuleTarget
interface.
Normally, you will use one of the source.onXxx(name[, target[, options]]) -> Rule
methods on the event source to define an event rule associated with
the specific activity. You can targets either via props, or add targets using
rule.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:
Repository repo; Project project; Rule onCommitRule = repo.onCommit("OnCommit", OnCommitOptions.builder() .target(new CodeBuildProject(project)) .branches(List.of("master")) .build());
You can add additional targets, with optional input
transformer
using eventRule.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:
Rule onCommitRule; Topic topic; onCommitRule.addTarget(SnsTopic.Builder.create(topic) .message(RuleTargetInput.fromText(String.format("A commit was pushed to the repository %s on branch %s", ReferenceEvent.getRepositoryName(), ReferenceEvent.getReferenceName()))) .build());
Or using an Object:
Rule onCommitRule; Topic topic; onCommitRule.addTarget(SnsTopic.Builder.create(topic) .message(RuleTargetInput.fromObject(Map.of( "DataType", String.format("custom_%s", EventField.fromPath("$.detail-type"))))) .build());
Scheduling
You 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:
import software.amazon.awscdk.services.events.Rule; import software.amazon.awscdk.services.events.Schedule; import software.amazon.awscdk.services.events.targets.EcsTask; import software.amazon.awscdk.services.ecs.Cluster; import software.amazon.awscdk.services.ecs.TaskDefinition; import software.amazon.awscdk.services.iam.Role; Cluster cluster; TaskDefinition taskDefinition; Role role; EcsTask ecsTaskTarget = EcsTask.Builder.create().cluster(cluster).taskDefinition(taskDefinition).role(role).build(); Rule.Builder.create(this, "ScheduleRule") .schedule(Schedule.cron(CronOptions.builder().minute("0").hour("4").build())) .targets(List.of(ecsTaskTarget)) .build();
If you want to specify Fargate platform version, set platformVersion
in EcsTask's props like the following example:
Cluster cluster; TaskDefinition taskDefinition; Role role; FargatePlatformVersion platformVersion = FargatePlatformVersion.VERSION1_4; EcsTask ecsTaskTarget = EcsTask.Builder.create().cluster(cluster).taskDefinition(taskDefinition).role(role).platformVersion(platformVersion).build();
Event Targets
The @aws-cdk/aws-events-targets
module includes classes that implement the IRuleTarget
interface 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 destination
Cross-account and cross-region targets
It's possible to have the source of the event and a target in separate AWS accounts and regions:
import software.amazon.awscdk.core.App; import software.amazon.awscdk.core.Stack; import software.amazon.awscdk.services.codebuild.*; import software.amazon.awscdk.services.codecommit.*; import software.amazon.awscdk.services.events.targets.*; App app = new App(); String account1 = "11111111111"; String account2 = "22222222222"; Stack stack1 = Stack.Builder.create(app, "Stack1").env(Environment.builder().account(account1).region("us-west-1").build()).build(); Repository repo = Repository.Builder.create(stack1, "Repository") .repositoryName("myrepository") .build(); Stack stack2 = Stack.Builder.create(app, "Stack2").env(Environment.builder().account(account2).region("us-east-1").build()).build(); Project project = Project.Builder.create(stack2, "Project").build(); repo.onCommit("OnCommit", OnCommitOptions.builder() .target(new CodeBuildProject(project)) .build());
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 target
- It will generate a rule in the target stack, with the provided target
- It 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 stack
For more information, see the AWS documentation on cross-account events.
Archiving
It is possible to archive all or some events sent to an event bus. It is then possible to replay these events.
EventBus bus = EventBus.Builder.create(this, "bus") .eventBusName("MyCustomEventBus") .build(); bus.archive("MyArchive", BaseArchiveProps.builder() .archiveName("MyCustomEventBusArchive") .description("MyCustomerEventBus Archive") .eventPattern(EventPattern.builder() .account(List.of(Stack.of(this).getAccount())) .build()) .retention(Duration.days(365)) .build());
Granting PutEvents to an existing EventBus
To import an existing EventBus into your CDK application, use EventBus.fromEventBusArn
, EventBus.fromEventBusAttributes
or EventBus.fromEventBusName
factory method.
Then, you can use the grantPutEventsTo
method to grant event:PutEvents
to the eventBus.
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.htmlFunction lambdaFunction; IEventBus eventBus = EventBus.fromEventBusArn(this, "ImportedEventBus", "arn:aws:events:us-east-1:111111111:event-bus/my-event-bus"); // now you can just call methods on the eventbus eventBus.grantPutEventsTo(lambdaFunction);
-
ClassDescriptionDefine an EventBridge Api Destination.A fluent builder for
ApiDestination
.The event API Destination properties.A builder forApiDestinationProps
An implementation forApiDestinationProps
Define an EventBridge Archive.A fluent builder forArchive
.The event archive properties.A builder forArchiveProps
An implementation forArchiveProps
Authorization type for an API Destination Connection.The event archive base properties.A builder forBaseArchiveProps
An implementation forBaseArchiveProps
A CloudFormationAWS::Events::ApiDestination
.A fluent builder forCfnApiDestination
.Properties for defining aCfnApiDestination
.A builder forCfnApiDestinationProps
An implementation forCfnApiDestinationProps
A CloudFormationAWS::Events::Archive
.A fluent builder forCfnArchive
.Properties for defining aCfnArchive
.A builder forCfnArchiveProps
An implementation forCfnArchiveProps
A CloudFormationAWS::Events::Connection
.Contains the API key authorization parameters for the connection.A builder forCfnConnection.ApiKeyAuthParametersProperty
An implementation forCfnConnection.ApiKeyAuthParametersProperty
Contains the authorization parameters to use for the connection.A builder forCfnConnection.AuthParametersProperty
An implementation forCfnConnection.AuthParametersProperty
Contains the Basic authorization parameters for the connection.A builder forCfnConnection.BasicAuthParametersProperty
An implementation forCfnConnection.BasicAuthParametersProperty
A fluent builder forCfnConnection
.Contains the OAuth authorization parameters to use for the connection.A builder forCfnConnection.ClientParametersProperty
An implementation forCfnConnection.ClientParametersProperty
Contains additional parameters for the connection.A builder forCfnConnection.ConnectionHttpParametersProperty
An implementation forCfnConnection.ConnectionHttpParametersProperty
Contains the OAuth authorization parameters to use for the connection.A builder forCfnConnection.OAuthParametersProperty
An implementation forCfnConnection.OAuthParametersProperty
Additional query string parameter for the connection.A builder forCfnConnection.ParameterProperty
An implementation forCfnConnection.ParameterProperty
Properties for defining aCfnConnection
.A builder forCfnConnectionProps
An implementation forCfnConnectionProps
A CloudFormationAWS::Events::Endpoint
.A fluent builder forCfnEndpoint
.The event buses the endpoint is associated with.A builder forCfnEndpoint.EndpointEventBusProperty
An implementation forCfnEndpoint.EndpointEventBusProperty
The failover configuration for an endpoint.A builder forCfnEndpoint.FailoverConfigProperty
An implementation forCfnEndpoint.FailoverConfigProperty
The primary Region of the endpoint.A builder forCfnEndpoint.PrimaryProperty
An implementation forCfnEndpoint.PrimaryProperty
Endpoints can replicate all events to the secondary Region.A builder forCfnEndpoint.ReplicationConfigProperty
An implementation forCfnEndpoint.ReplicationConfigProperty
The routing configuration of the endpoint.A builder forCfnEndpoint.RoutingConfigProperty
An implementation forCfnEndpoint.RoutingConfigProperty
The secondary Region that processes events when failover is triggered or replication is enabled.A builder forCfnEndpoint.SecondaryProperty
An implementation forCfnEndpoint.SecondaryProperty
Properties for defining aCfnEndpoint
.A builder forCfnEndpointProps
An implementation forCfnEndpointProps
A CloudFormationAWS::Events::EventBus
.A fluent builder forCfnEventBus
.A key-value pair associated with an AWS resource.A builder forCfnEventBus.TagEntryProperty
An implementation forCfnEventBus.TagEntryProperty
A CloudFormationAWS::Events::EventBusPolicy
.A fluent builder forCfnEventBusPolicy
.A JSON string which you can use to limit the event bus permissions you are granting to only accounts that fulfill the condition.A builder forCfnEventBusPolicy.ConditionProperty
An implementation forCfnEventBusPolicy.ConditionProperty
Properties for defining aCfnEventBusPolicy
.A builder forCfnEventBusPolicyProps
An implementation forCfnEventBusPolicyProps
Properties for defining aCfnEventBus
.A builder forCfnEventBusProps
An implementation forCfnEventBusProps
A CloudFormationAWS::Events::Rule
.This structure specifies the VPC subnets and security groups for the task, and whether a public IP address is to be used.A builder forCfnRule.AwsVpcConfigurationProperty
An implementation forCfnRule.AwsVpcConfigurationProperty
The array properties for the submitted job, such as the size of the array.A builder forCfnRule.BatchArrayPropertiesProperty
An implementation forCfnRule.BatchArrayPropertiesProperty
The custom parameters to be used when the target is an AWS Batch job.A builder forCfnRule.BatchParametersProperty
An implementation forCfnRule.BatchParametersProperty
The retry strategy to use for failed jobs, if the target is an AWS Batch job.A builder forCfnRule.BatchRetryStrategyProperty
An implementation forCfnRule.BatchRetryStrategyProperty
A fluent builder forCfnRule
.The details of a capacity provider strategy.A builder forCfnRule.CapacityProviderStrategyItemProperty
An implementation forCfnRule.CapacityProviderStrategyItemProperty
ADeadLetterConfig
object that contains information about a dead-letter queue configuration.A builder forCfnRule.DeadLetterConfigProperty
An implementation forCfnRule.DeadLetterConfigProperty
The custom parameters to be used when the target is an Amazon ECS task.A builder forCfnRule.EcsParametersProperty
An implementation forCfnRule.EcsParametersProperty
These are custom parameter to be used when the target is an API Gateway APIs or EventBridge ApiDestinations.A builder forCfnRule.HttpParametersProperty
An implementation forCfnRule.HttpParametersProperty
Contains the parameters needed for you to provide custom input to a target based on one or more pieces of data extracted from the event.A builder forCfnRule.InputTransformerProperty
An implementation forCfnRule.InputTransformerProperty
This object enables you to specify a JSON path to extract from the event and use as the partition key for the Amazon Kinesis data stream, so that you can control the shard to which the event goes.A builder forCfnRule.KinesisParametersProperty
An implementation forCfnRule.KinesisParametersProperty
This structure specifies the network configuration for an ECS task.A builder forCfnRule.NetworkConfigurationProperty
An implementation forCfnRule.NetworkConfigurationProperty
An object representing a constraint on task placement.A builder forCfnRule.PlacementConstraintProperty
An implementation forCfnRule.PlacementConstraintProperty
The task placement strategy for a task or service.A builder forCfnRule.PlacementStrategyProperty
An implementation forCfnRule.PlacementStrategyProperty
These are custom parameters to be used when the target is a Amazon Redshift cluster to invoke the Amazon Redshift Data API ExecuteStatement based on EventBridge events.A builder forCfnRule.RedshiftDataParametersProperty
An implementation forCfnRule.RedshiftDataParametersProperty
ARetryPolicy
object that includes information about the retry policy settings.A builder forCfnRule.RetryPolicyProperty
An implementation forCfnRule.RetryPolicyProperty
This parameter contains the criteria (either InstanceIds or a tag) used to specify which EC2 instances are to be sent the command.A builder forCfnRule.RunCommandParametersProperty
An implementation forCfnRule.RunCommandParametersProperty
Information about the EC2 instances that are to be sent the command, specified as key-value pairs.A builder forCfnRule.RunCommandTargetProperty
An implementation forCfnRule.RunCommandTargetProperty
Name/Value pair of a parameter to start execution of a SageMaker Model Building Pipeline.A builder forCfnRule.SageMakerPipelineParameterProperty
An implementation forCfnRule.SageMakerPipelineParameterProperty
These are custom parameters to use when the target is a SageMaker Model Building Pipeline that starts based on EventBridge events.A builder forCfnRule.SageMakerPipelineParametersProperty
An implementation forCfnRule.SageMakerPipelineParametersProperty
This structure includes the custom parameter to be used when the target is an SQS FIFO queue.A builder forCfnRule.SqsParametersProperty
An implementation forCfnRule.SqsParametersProperty
A key-value pair associated with an ECS Target of an EventBridge rule.A builder forCfnRule.TagProperty
An implementation forCfnRule.TagProperty
Targets are the resources to be invoked when a rule is triggered.A builder forCfnRule.TargetProperty
An implementation forCfnRule.TargetProperty
Properties for defining aCfnRule
.A builder forCfnRuleProps
An implementation forCfnRuleProps
Define an EventBridge Connection.A fluent builder forConnection
.Interface with properties necessary to import a reusable Connection.A builder forConnectionAttributes
An implementation forConnectionAttributes
An API Destination Connection.A builder forConnectionProps
An implementation forConnectionProps
Options to configure a cron expression.A builder forCronOptions
An implementation forCronOptions
Define an EventBridge EventBus.A fluent builder forEventBus
.Interface with properties necessary to import a reusable EventBus.A builder forEventBusAttributes
An implementation forEventBusAttributes
Properties to define an event bus.A builder forEventBusProps
An implementation forEventBusProps
Represents a field in the event pattern.Events in Amazon CloudWatch Events are represented as JSON objects.A builder forEventPattern
An implementation forEventPattern
Supported HTTP operations.An additional HTTP parameter to send along with the OAuth request.Interface for API Destinations.Internal default implementation forIApiDestination
.A proxy class which represents a concrete javascript instance of this type.Interface for EventBus Connections.Internal default implementation forIConnection
.A proxy class which represents a concrete javascript instance of this type.Interface which all EventBus based classes MUST implement.Internal default implementation forIEventBus
.A proxy class which represents a concrete javascript instance of this type.Represents an EventBridge Rule.Internal default implementation forIRule
.A proxy class which represents a concrete javascript instance of this type.An abstract target for EventRules.Internal default implementation forIRuleTarget
.A proxy class which represents a concrete javascript instance of this type.Properties forAuthorization.oauth()
.A builder forOAuthAuthorizationProps
An implementation forOAuthAuthorizationProps
Standard set of options foronXxx
event handlers on construct.A builder forOnEventOptions
An implementation forOnEventOptions
Defines an EventBridge Rule in this stack.A fluent builder forRule
.Properties for defining an EventBridge Rule.A builder forRuleProps
An implementation forRuleProps
Properties for an event rule target.A builder forRuleTargetConfig
An implementation forRuleTargetConfig
The input to send to the event target.The input properties for an event target.A builder forRuleTargetInputProperties
An implementation forRuleTargetInputProperties
Schedule for scheduled event rules.