AWSCDK::Events

53 types

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:

repo = nil # AWSCDK::Codecommit::Repository
project = nil # AWSCDK::CodeBuild::Project


on_commit_rule = repo.on_commit("OnCommit", {
    target: AWSCDK::EventsTargets::CodeBuildProject.new(project),
    event_pattern: {
        detail: {
            reference_type: ["branch"],
        },
    },
    branches: AWSCDK::Events::Match.prefix("main"),
})

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:

on_commit_rule = nil # AWSCDK::Events::Rule
topic = nil # AWSCDK::SNS::Topic


on_commit_rule.add_target(AWSCDK::EventsTargets::SNSTopic.new(topic, {
    message: AWSCDK::Events::RuleTargetInput.from_text("A commit was pushed to the repository #{AWSCDK::Codecommit::ReferenceEvent.repository_name} on branch #{AWSCDK::Codecommit::ReferenceEvent.reference_name}"),
}))

Or using an Object:

on_commit_rule = nil # AWSCDK::Events::Rule
topic = nil # AWSCDK::SNS::Topic


on_commit_rule.add_target(AWSCDK::EventsTargets::SNSTopic.new(topic, {
    message: AWSCDK::Events::RuleTargetInput.from_object({
        DataType: "custom_#{AWSCDK::Events::EventField.from_path("$.detail-type")}",
    }),
}))

Role

You can specify an IAM Role:

role = nil # AWSCDK::IAM::IRole


AWSCDK::Events::Rule.new(self, "MyRule", {
    schedule: AWSCDK::Events::Schedule.cron({minute: "0", hour: "4"}),
    role: role,
})

Note: If you're setting an event bus in another account as the target and that account granted permission to your account through an organization instead of directly by the account ID, you must specify a RoleArn with proper permissions in the Target structure, instead of here in this parameter.

Matchers

To define a pattern, use the Match class, 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:

rule = AWSCDK::Events::Rule.new(self, "rule", {
    event_pattern: {
        detail: {
            object: {
                # Matchers may appear at any level
                size: AWSCDK::Events::Match.greater_than(1024),
            },

            # 'OR' condition
            "source-storage-class" => AWSCDK::Events::Match.any_of(AWSCDK::Events::Match.prefix("GLACIER"), AWSCDK::Events::Match.exact_string("DEEP_ARCHIVE")),
        },

        # If you prefer, you can use a low level array of strings, as directly consumed by EventBridge
        source: ["aws.s3"],

        region: AWSCDK::Events::Match.anything_but_prefix("us-gov"),
    },
})

Matches can also be made case-insensitive, or make use of wildcard matches. For example, to match object create events for buckets whose name starts with raw-, for objects with key matching the pattern path/to/object/*.txt and the requester ends with .AMAZONAWS.COM:

rule = AWSCDK::Events::Rule.new(self, "rule", {
    event_pattern: {
        detail: {
            bucket: {
                name: AWSCDK::Events::Match.prefix_equals_ignore_case("raw-"),
            },

            object: {
                key: AWSCDK::Events::Match.wildcard("path/to/object/*.txt"),
            },

            requester: AWSCDK::Events::Match.suffix_equals_ignore_case(".AMAZONAWS.COM"),
        },
        detail_type: AWSCDK::Events::Match.equals_ignore_case("object created"),
    },
})

The "anything but" matchers allow you to specify multiple arguments. For example:

rule = AWSCDK::Events::Rule.new(self, "rule", {
    event_pattern: {
        region: AWSCDK::Events::Match.anything_but("us-east-1", "us-east-2", "us-west-1", "us-west-2"),

        detail: {
            bucket: {
                name: AWSCDK::Events::Match.anything_but_prefix("foo", "bar", "baz"),
            },

            object: {
                key: AWSCDK::Events::Match.anything_but_suffix(".gif", ".png", ".jpg"),
            },

            requester: AWSCDK::Events::Match.anything_but_wildcard("*.amazonaws.com", "123456789012"),
        },
        detail_type: AWSCDK::Events::Match.anything_but_equals_ignore_case("object created", "object deleted"),
    },
})

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:

require 'aws-cdk-lib'

cluster = nil # AWSCDK::ECS::Cluster
task_definition = nil # AWSCDK::ECS::TaskDefinition
role = nil # AWSCDK::IAM::Role


ecs_task_target = AWSCDK::EventsTargets::ECSTask.new({cluster: cluster, task_definition: task_definition, role: role})

AWSCDK::Events::Rule.new(self, "ScheduleRule", {
    schedule: AWSCDK::Events::Schedule.cron({minute: "0", hour: "4"}),
    targets: [ecs_task_target],
})

If you want to specify Fargate platform version, set platform_version in EcsTask's props like the following example:

cluster = nil # AWSCDK::ECS::Cluster
task_definition = nil # AWSCDK::ECS::TaskDefinition
role = nil # AWSCDK::IAM::Role


platform_version = AWSCDK::ECS::FargatePlatformVersion::VERSION1_4
ecs_task_target = AWSCDK::EventsTargets::ECSTask.new({cluster: cluster, task_definition: task_definition, role: role, platform_version: platform_version})

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:

require 'aws-cdk-lib'

app = AWSCDK::App.new

account1 = "11111111111"
account2 = "22222222222"

stack1 = AWSCDK::Stack.new(app, "Stack1", {env: {account: account1, region: "us-west-1"}})
repo = AWSCDK::Codecommit::Repository.new(stack1, "Repository", {
    repository_name: "myrepository",
})

stack2 = AWSCDK::Stack.new(app, "Stack2", {env: {account: account2, region: "us-east-1"}})
project = AWSCDK::CodeBuild::Project.new(stack2, "Project", {})

repo.on_commit("OnCommit", {
    target: AWSCDK::EventsTargets::CodeBuildProject.new(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.

bus = AWSCDK::Events::EventBus.new(self, "bus", {
    event_bus_name: "MyCustomEventBus",
    description: "MyCustomEventBus",
})

bus.archive("MyArchive", {
    archive_name: "MyCustomEventBusArchive",
    description: "MyCustomerEventBus Archive",
    event_pattern: {
        account: [AWSCDK::Stack.of(self).],
    },
    retention: AWSCDK::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 dead_letter_queue property of the EventBus construct.

require 'aws-cdk-lib'


dlq = AWSCDK::SQS::Queue.new(self, "DLQ")

bus = AWSCDK::Events::EventBus.new(self, "Bus", {
    dead_letter_queue: 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 grant_put_events_to method to grant event:PutEvents to the eventBus.

lambda_function = nil # AWSCDK::Lambda::Function


event_bus = AWSCDK::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 eventbus
event_bus.grant_put_events_to(lambda_function)

Use a customer managed key

To use a customer managed key for events on the event bus, use the kms_key attribute.

require 'aws-cdk-lib'

kms_key = nil # AWSCDK::KMS::IKey


AWSCDK::Events::EventBus.new(self, "Bus", {
    kms_key: kms_key,
})

To use a customer managed key for an archive, use the kms_key attribute.

Note: When you attach a customer managed key to either an EventBus or an Archive, a policy that allows EventBridge to interact with your resource will be added.

require 'aws-cdk-lib'

kms_key = nil # AWSCDK::KMS::IKey


stack = AWSCDK::Stack.new

event_bus = AWSCDK::Events::EventBus.new(stack, "Bus")

archive = AWSCDK::Events::Archive.new(stack, "Archive", {
    kms_key: kms_key,
    source_event_bus: event_bus,
    event_pattern: {
        source: ["aws.ec2"],
    },
})

To enable archives on an event bus, customers have the choice of using either an AWS owned key or a customer managed key. Note that schema discovery is not supported for event buses encrypted using a customer managed key. To enable schema discovery on an event bus, choose to use an AWS owned key. For more information, see KMS key options for event bus encryption and Encrypting event buses with customer managed keys.

Configuring logging

To configure logging for an Event Bus, leverage the LogConfig property. It allows different level of logging (NONE, INFO, TRACE, ERROR) and whether to include details or not.

require 'aws-cdk-lib'


bus = AWSCDK::Events::EventBus.new(self, "Bus", {
    log_config: {
        include_detail: AWSCDK::Events::IncludeDetail::FULL,
        level: AWSCDK::Events::Level::TRACE,
    },
})

Note: Configuring logging on the event bus is required when using vended logs. Vended logs require that the event bus has logging enabled with the appropriate log configuration before logs can be delivered to the destination.

See more Specifying event bus log level

API Reference

Classes 20

APIDestinationDefine an EventBridge Api Destination. ArchiveDefine an EventBridge Archive. AuthorizationAuthorization type for an API Destination Connection. CfnAPIDestinationCreates an API destination, which is an HTTP invocation endpoint configured as a target fo CfnArchiveCreates an archive of events with the specified settings. CfnConnectionCreates a connection. CfnEndpointA global endpoint used to improve your application's availability by making it regional-fa CfnEventBusSpecifies an event bus within your account. CfnEventBusPolicyRunning `PutPermission` permits the specified AWS account or AWS organization to put event CfnRuleCreates or updates the specified rule. ConnectionDefine an EventBridge Connection. EventBusDefine an EventBridge EventBus. EventBusGrantsCollection of grant methods for a IEventBusRef. EventBusPolicyThe policy for an Event Bus. EventFieldRepresents a field in the event pattern. HttpParameterAn additional HTTP parameter to send along with the OAuth request. MatchAn event pattern matcher. RuleDefines an EventBridge Rule in this stack. RuleTargetInputThe input to send to the event target. ScheduleSchedule for scheduled event rules.

Interfaces 30

APIDestinationAttributesThe properties to import an existing Api Destination. APIDestinationPropsThe event API Destination properties. ArchivePropsThe event archive properties. BaseArchivePropsThe event archive base properties. CfnAPIDestinationPropsProperties for defining a `CfnApiDestination`. CfnArchivePropsProperties for defining a `CfnArchive`. CfnConnectionPropsProperties for defining a `CfnConnection`. CfnEndpointPropsProperties for defining a `CfnEndpoint`. CfnEventBusPolicyPropsProperties for defining a `CfnEventBusPolicy`. CfnEventBusPropsProperties for defining a `CfnEventBus`. CfnRulePropsProperties for defining a `CfnRule`. ConnectionAttributesInterface with properties necessary to import a reusable Connection. ConnectionPropsAn API Destination Connection. CronOptionsOptions to configure a cron expression. EventBusAttributesInterface with properties necessary to import a reusable EventBus. EventBusPolicyPropsProperties to associate Event Buses with a policy. EventBusPropsProperties to define an event bus. EventCommonOptionsCommon options for Events. EventPatternEvents in Amazon CloudWatch Events are represented as JSON objects. For more information a IAPIDestinationInterface for API Destinations. IConnectionInterface for EventBus Connections. IEventBusInterface which all EventBus based classes MUST implement. IRuleRepresents an EventBridge Rule. IRuleTargetAn abstract target for EventRules. LogConfigInterface for Logging Configuration of the Event Bus. OAuthAuthorizationPropsProperties for `Authorization.oauth()`. OnEventOptionsStandard set of options for `onXxx` event handlers on construct. RulePropsProperties for defining an EventBridge Rule. RuleTargetConfigProperties for an event rule target. RuleTargetInputPropertiesThe input properties for an event target.

Enums 3

HttpMethodSupported HTTP operations. IncludeDetailWhether EventBridge include detailed event information in the records it generates. LevelThe level of logging detail to include.