Namespace Amazon.CDK.AWS.Events
Amazon EventBridge Construct Library
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.
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;
var onCommitRule = repo.OnCommit("OnCommit", new OnCommitOptions {
Target = new CodeBuildProject(project),
Branches = new [] { "master" }
});
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(new SnsTopic(topic, new SnsTopicProps {
Message = RuleTargetInput.FromText($"A commit was pushed to the repository {codecommit.ReferenceEvent.repositoryName} on branch {codecommit.ReferenceEvent.referenceName}")
}));
Or using an Object:
Rule onCommitRule;
Topic topic;
onCommitRule.AddTarget(new SnsTopic(topic, new SnsTopicProps {
Message = RuleTargetInput.FromObject(new Dictionary<string, string> {
{ "DataType", $"custom_{events.EventField.fromPath('$.detail-type')}" }
})
}));
To define a pattern, use the matcher API, which provides a number of factory methods to declare different logical predicates. For example, to match all S3 events for objects larger than 1024 bytes, stored using one of the storage classes Glacier, Glacier IR or Deep Archive and coming from any region other than the AWS GovCloud ones:
var rule = new Rule(this, "rule", new RuleProps {
EventPattern = new EventPattern {
Detail = new Dictionary<string, object> {
{ "object", new Dictionary<string, string[]> {
// Matchers may appear at any level
{ "size", Match.GreaterThan(1024) }
} },
// 'OR' condition
{ "source-storage-class", Match.AnyOf(Match.Prefix("GLACIER"), Match.ExactString("DEEP_ARCHIVE")) }
},
DetailType = Match.EqualsIgnoreCase("object created"),
// If you prefer, you can use a low level array of strings, as directly consumed by EventBridge
Source = new [] { "aws.s3" },
Region = Match.AnythingButPrefix("us-gov")
}
});
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:
using Amazon.CDK.AWS.Events;
using Amazon.CDK.AWS.Events.Targets;
using Amazon.CDK.AWS.ECS;
using Amazon.CDK.AWS.IAM;
Cluster cluster;
TaskDefinition taskDefinition;
Role role;
var ecsTaskTarget = new EcsTask(new EcsTaskProps { Cluster = cluster, TaskDefinition = taskDefinition, Role = role });
new Rule(this, "ScheduleRule", new RuleProps {
Schedule = Schedule.Cron(new CronOptions { Minute = "0", Hour = "4" }),
Targets = new [] { ecsTaskTarget }
});
If you want to specify Fargate platform version, set platformVersion
in EcsTask's props like the following example:
Cluster cluster;
TaskDefinition taskDefinition;
Role role;
var platformVersion = FargatePlatformVersion.VERSION1_4;
var ecsTaskTarget = new EcsTask(new EcsTaskProps { Cluster = cluster, TaskDefinition = taskDefinition, Role = role, PlatformVersion = platformVersion });
Event Targets
The aws-cdk-lib/aws-events-targets
module includes classes that implement the IRuleTarget
interface for various AWS services.
See the README of the aws-cdk-lib/aws-events-targets
module for more information on supported targets.
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:
using Amazon.CDK;
using Amazon.CDK.AWS.CodeBuild;
using Amazon.CDK.AWS.CodeCommit;
using Amazon.CDK.AWS.Events.Targets;
var app = new App();
var account1 = "11111111111";
var account2 = "22222222222";
var stack1 = new Stack(app, "Stack1", new StackProps { Env = new Environment { Account = account1, Region = "us-west-1" } });
var repo = new Repository(stack1, "Repository", new RepositoryProps {
RepositoryName = "myrepository"
});
var stack2 = new Stack(app, "Stack2", new StackProps { Env = new Environment { Account = account2, Region = "us-east-1" } });
var project = new Project(stack2, "Project", new ProjectProps { });
repo.OnCommit("OnCommit", new OnCommitOptions {
Target = new CodeBuildProject(project)
});
In this situation, the CDK will wire the 2 accounts together:
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.
var bus = new EventBus(this, "bus", new EventBusProps {
EventBusName = "MyCustomEventBus",
Description = "MyCustomEventBus"
});
bus.Archive("MyArchive", new BaseArchiveProps {
ArchiveName = "MyCustomEventBusArchive",
Description = "MyCustomerEventBus Archive",
EventPattern = new EventPattern {
Account = new [] { Stack.Of(this).Account }
},
Retention = Duration.Days(365)
});
Dead-Letter Queue for EventBus
It is possible to configure a Dead Letter Queue for an EventBus. This is useful when you want to capture events that could not be delivered to any of the targets.
To configure a Dead Letter Queue for an EventBus, you can use the deadLetterQueue
property of the EventBus
construct.
using Amazon.CDK.AWS.SQS;
var dlq = new Queue(this, "DLQ");
var bus = new EventBus(this, "Bus", new EventBusProps {
DeadLetterQueue = dlq
});
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.
Function lambdaFunction;
var 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);
Use a customer managed key
To use a customer managed key for events on the event bus, use the kmsKey
attribute.
using Amazon.CDK.AWS.KMS;
IKey kmsKey;
new EventBus(this, "Bus", new EventBusProps {
KmsKey = kmsKey
});
Note: Archives and schema discovery are not supported for event buses encrypted using a customer managed key. To enable archives or schema discovery on an event bus, choose to use an AWS owned key. For more information, see KMS key options for event bus encryption.
Classes
ApiDestination | Define an EventBridge Api Destination. |
ApiDestinationAttributes | The properties to import an existing Api Destination. |
ApiDestinationProps | The event API Destination properties. |
Archive | Define an EventBridge Archive. |
ArchiveProps | The event archive properties. |
Authorization | Authorization type for an API Destination Connection. |
BaseArchiveProps | The event archive base properties. |
CfnApiDestination | Creates an API destination, which is an HTTP invocation endpoint configured as a target for events. |
CfnApiDestinationProps | Properties for defining a |
CfnArchive | Creates an archive of events with the specified settings. |
CfnArchiveProps | Properties for defining a |
CfnConnection | Creates a connection. |
CfnConnection.ApiKeyAuthParametersProperty | Contains the API key authorization parameters for the connection. |
CfnConnection.AuthParametersProperty | Contains the authorization parameters to use for the connection. |
CfnConnection.BasicAuthParametersProperty | Contains the Basic authorization parameters for the connection. |
CfnConnection.ClientParametersProperty | Contains the OAuth authorization parameters to use for the connection. |
CfnConnection.ConnectionHttpParametersProperty | Contains additional parameters for the connection. |
CfnConnection.OAuthParametersProperty | Contains the OAuth authorization parameters to use for the connection. |
CfnConnection.ParameterProperty | Additional query string parameter for the connection. |
CfnConnectionProps | Properties for defining a |
CfnEndpoint | A global endpoint used to improve your application's availability by making it regional-fault tolerant. |
CfnEndpoint.EndpointEventBusProperty | The event buses the endpoint is associated with. |
CfnEndpoint.FailoverConfigProperty | The failover configuration for an endpoint. |
CfnEndpoint.PrimaryProperty | The primary Region of the endpoint. |
CfnEndpoint.ReplicationConfigProperty | Endpoints can replicate all events to the secondary Region. |
CfnEndpoint.RoutingConfigProperty | The routing configuration of the endpoint. |
CfnEndpoint.SecondaryProperty | The secondary Region that processes events when failover is triggered or replication is enabled. |
CfnEndpointProps | Properties for defining a |
CfnEventBus | Specifies an event bus within your account. |
CfnEventBus.DeadLetterConfigProperty | Configuration details of the Amazon SQS queue for EventBridge to use as a dead-letter queue (DLQ). |
CfnEventBusPolicy | Running |
CfnEventBusPolicy.ConditionProperty | A JSON string which you can use to limit the event bus permissions you are granting to only accounts that fulfill the condition. |
CfnEventBusPolicyProps | Properties for defining a |
CfnEventBusProps | Properties for defining a |
CfnRule | Creates or updates the specified rule. |
CfnRule.AppSyncParametersProperty | Contains the GraphQL operation to be parsed and executed, if the event target is an AWS AppSync API. |
CfnRule.AwsVpcConfigurationProperty | This structure specifies the VPC subnets and security groups for the task, and whether a public IP address is to be used. |
CfnRule.BatchArrayPropertiesProperty | The array properties for the submitted job, such as the size of the array. |
CfnRule.BatchParametersProperty | The custom parameters to be used when the target is an AWS Batch job. |
CfnRule.BatchRetryStrategyProperty | The retry strategy to use for failed jobs, if the target is an AWS Batch job. |
CfnRule.CapacityProviderStrategyItemProperty | The details of a capacity provider strategy. |
CfnRule.DeadLetterConfigProperty | Configuration details of the Amazon SQS queue for EventBridge to use as a dead-letter queue (DLQ). |
CfnRule.EcsParametersProperty | The custom parameters to be used when the target is an Amazon ECS task. |
CfnRule.HttpParametersProperty | These are custom parameter to be used when the target is an API Gateway APIs or EventBridge ApiDestinations. |
CfnRule.InputTransformerProperty | 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. |
CfnRule.KinesisParametersProperty | 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. |
CfnRule.NetworkConfigurationProperty | This structure specifies the network configuration for an ECS task. |
CfnRule.PlacementConstraintProperty | An object representing a constraint on task placement. |
CfnRule.PlacementStrategyProperty | The task placement strategy for a task or service. |
CfnRule.RedshiftDataParametersProperty | 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. |
CfnRule.RetryPolicyProperty | A |
CfnRule.RunCommandParametersProperty | This parameter contains the criteria (either InstanceIds or a tag) used to specify which EC2 instances are to be sent the command. |
CfnRule.RunCommandTargetProperty | Information about the EC2 instances that are to be sent the command, specified as key-value pairs. |
CfnRule.SageMakerPipelineParameterProperty | Name/Value pair of a parameter to start execution of a SageMaker Model Building Pipeline. |
CfnRule.SageMakerPipelineParametersProperty | These are custom parameters to use when the target is a SageMaker Model Building Pipeline that starts based on EventBridge events. |
CfnRule.SqsParametersProperty | This structure includes the custom parameter to be used when the target is an SQS FIFO queue. |
CfnRule.TagProperty | A key-value pair associated with an ECS Target of an EventBridge rule. |
CfnRule.TargetProperty | Targets are the resources to be invoked when a rule is triggered. |
CfnRuleProps | Properties for defining a |
Connection | Define an EventBridge Connection. |
ConnectionAttributes | Interface with properties necessary to import a reusable Connection. |
ConnectionProps | An API Destination Connection. |
CronOptions | Options to configure a cron expression. |
EventBus | Define an EventBridge EventBus. |
EventBusAttributes | Interface with properties necessary to import a reusable EventBus. |
EventBusPolicy | The policy for an Event Bus. |
EventBusPolicyProps | Properties to associate Event Buses with a policy. |
EventBusProps | Properties to define an event bus. |
EventCommonOptions | Common options for Events. |
EventField | Represents a field in the event pattern. |
EventPattern | Events in Amazon CloudWatch Events are represented as JSON objects. For more information about JSON objects, see RFC 7159. |
HttpMethod | Supported HTTP operations. |
HttpParameter | An additional HTTP parameter to send along with the OAuth request. |
Match | An event pattern matcher. |
OAuthAuthorizationProps | Properties for |
OnEventOptions | Standard set of options for |
Rule | Defines an EventBridge Rule in this stack. |
RuleProps | Properties for defining an EventBridge Rule. |
RuleTargetConfig | Properties for an event rule target. |
RuleTargetInput | The input to send to the event target. |
RuleTargetInputProperties | The input properties for an event target. |
Schedule | Schedule for scheduled event rules. |
Interfaces
CfnConnection.IApiKeyAuthParametersProperty | Contains the API key authorization parameters for the connection. |
CfnConnection.IAuthParametersProperty | Contains the authorization parameters to use for the connection. |
CfnConnection.IBasicAuthParametersProperty | Contains the Basic authorization parameters for the connection. |
CfnConnection.IClientParametersProperty | Contains the OAuth authorization parameters to use for the connection. |
CfnConnection.IConnectionHttpParametersProperty | Contains additional parameters for the connection. |
CfnConnection.IOAuthParametersProperty | Contains the OAuth authorization parameters to use for the connection. |
CfnConnection.IParameterProperty | Additional query string parameter for the connection. |
CfnEndpoint.IEndpointEventBusProperty | The event buses the endpoint is associated with. |
CfnEndpoint.IFailoverConfigProperty | The failover configuration for an endpoint. |
CfnEndpoint.IPrimaryProperty | The primary Region of the endpoint. |
CfnEndpoint.IReplicationConfigProperty | Endpoints can replicate all events to the secondary Region. |
CfnEndpoint.IRoutingConfigProperty | The routing configuration of the endpoint. |
CfnEndpoint.ISecondaryProperty | The secondary Region that processes events when failover is triggered or replication is enabled. |
CfnEventBus.IDeadLetterConfigProperty | Configuration details of the Amazon SQS queue for EventBridge to use as a dead-letter queue (DLQ). |
CfnEventBusPolicy.IConditionProperty | A JSON string which you can use to limit the event bus permissions you are granting to only accounts that fulfill the condition. |
CfnRule.IAppSyncParametersProperty | Contains the GraphQL operation to be parsed and executed, if the event target is an AWS AppSync API. |
CfnRule.IAwsVpcConfigurationProperty | This structure specifies the VPC subnets and security groups for the task, and whether a public IP address is to be used. |
CfnRule.IBatchArrayPropertiesProperty | The array properties for the submitted job, such as the size of the array. |
CfnRule.IBatchParametersProperty | The custom parameters to be used when the target is an AWS Batch job. |
CfnRule.IBatchRetryStrategyProperty | The retry strategy to use for failed jobs, if the target is an AWS Batch job. |
CfnRule.ICapacityProviderStrategyItemProperty | The details of a capacity provider strategy. |
CfnRule.IDeadLetterConfigProperty | Configuration details of the Amazon SQS queue for EventBridge to use as a dead-letter queue (DLQ). |
CfnRule.IEcsParametersProperty | The custom parameters to be used when the target is an Amazon ECS task. |
CfnRule.IHttpParametersProperty | These are custom parameter to be used when the target is an API Gateway APIs or EventBridge ApiDestinations. |
CfnRule.IInputTransformerProperty | 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. |
CfnRule.IKinesisParametersProperty | 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. |
CfnRule.INetworkConfigurationProperty | This structure specifies the network configuration for an ECS task. |
CfnRule.IPlacementConstraintProperty | An object representing a constraint on task placement. |
CfnRule.IPlacementStrategyProperty | The task placement strategy for a task or service. |
CfnRule.IRedshiftDataParametersProperty | 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. |
CfnRule.IRetryPolicyProperty | A |
CfnRule.IRunCommandParametersProperty | This parameter contains the criteria (either InstanceIds or a tag) used to specify which EC2 instances are to be sent the command. |
CfnRule.IRunCommandTargetProperty | Information about the EC2 instances that are to be sent the command, specified as key-value pairs. |
CfnRule.ISageMakerPipelineParameterProperty | Name/Value pair of a parameter to start execution of a SageMaker Model Building Pipeline. |
CfnRule.ISageMakerPipelineParametersProperty | These are custom parameters to use when the target is a SageMaker Model Building Pipeline that starts based on EventBridge events. |
CfnRule.ISqsParametersProperty | This structure includes the custom parameter to be used when the target is an SQS FIFO queue. |
CfnRule.ITagProperty | A key-value pair associated with an ECS Target of an EventBridge rule. |
CfnRule.ITargetProperty | Targets are the resources to be invoked when a rule is triggered. |
IApiDestination | Interface for API Destinations. |
IApiDestinationAttributes | The properties to import an existing Api Destination. |
IApiDestinationProps | The event API Destination properties. |
IArchiveProps | The event archive properties. |
IBaseArchiveProps | The event archive base properties. |
ICfnApiDestinationProps | Properties for defining a |
ICfnArchiveProps | Properties for defining a |
ICfnConnectionProps | Properties for defining a |
ICfnEndpointProps | Properties for defining a |
ICfnEventBusPolicyProps | Properties for defining a |
ICfnEventBusProps | Properties for defining a |
ICfnRuleProps | Properties for defining a |
IConnection | Interface for EventBus Connections. |
IConnectionAttributes | Interface with properties necessary to import a reusable Connection. |
IConnectionProps | An API Destination Connection. |
ICronOptions | Options to configure a cron expression. |
IEventBus | Interface which all EventBus based classes MUST implement. |
IEventBusAttributes | Interface with properties necessary to import a reusable EventBus. |
IEventBusPolicyProps | Properties to associate Event Buses with a policy. |
IEventBusProps | Properties to define an event bus. |
IEventCommonOptions | Common options for Events. |
IEventPattern | Events in Amazon CloudWatch Events are represented as JSON objects. For more information about JSON objects, see RFC 7159. |
IOAuthAuthorizationProps | Properties for |
IOnEventOptions | Standard set of options for |
IRule | Represents an EventBridge Rule. |
IRuleProps | Properties for defining an EventBridge Rule. |
IRuleTarget | An abstract target for EventRules. |
IRuleTargetConfig | Properties for an event rule target. |
IRuleTargetInputProperties | The input properties for an event target. |