Skip to content
v2.273.0

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.

  • 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:

ts
declare const repo: codecommit.Repository;
declare const project: codebuild.Project;

const onCommitRule = repo.onCommit('OnCommit', {
  target: new targets.CodeBuildProject(project),
  eventPattern: {
    detail: {
      referenceType: ['branch'],
    }
  },
  branches: events.Match.prefix('main')
});
python
# repo: codecommit.Repository
# project: codebuild.Project


on_commit_rule = repo.on_commit("OnCommit",
    target=targets.CodeBuildProject(project),
    event_pattern=events.EventPattern(
        detail={
            "reference_type": ["branch"]
        }
    ),
    branches=events.Match.prefix("main")
)
java
Repository repo;
Project project;


Rule onCommitRule = repo.onCommit("OnCommit", OnCommitOptions.builder()
        .target(new CodeBuildProject(project))
        .eventPattern(EventPattern.builder()
                .detail(Map.of(
                        "referenceType", List.of("branch")))
                .build())
        .branches(Match.prefix("main"))
        .build());
csharp
Repository repo;
Project project;


var onCommitRule = repo.OnCommit("OnCommit", new OnCommitOptions {
    Target = new CodeBuildProject(project),
    EventPattern = new EventPattern {
        Detail = new Dictionary<string, object> {
            { "referenceType", new [] { "branch" } }
        }
    },
    Branches = Match.Prefix("main")
});
go
var repo Repository
var project Project


onCommitRule := repo.onCommit(jsii.String("OnCommit"), &OnCommitOptions{
	Target: targets.NewCodeBuildProject(project),
	EventPattern: &EventPattern{
		Detail: map[string]interface{}{
			"referenceType": []interface{}{
				jsii.String("branch"),
			},
		},
	},
	Branches: events.Match_Prefix(jsii.String("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:

ts
declare const onCommitRule: events.Rule;
declare const topic: sns.Topic;

onCommitRule.addTarget(new targets.SnsTopic(topic, {
  message: events.RuleTargetInput.fromText(
    `A commit was pushed to the repository ${codecommit.ReferenceEvent.repositoryName} on branch ${codecommit.ReferenceEvent.referenceName}`
  )
}));
python
# on_commit_rule: events.Rule
# topic: sns.Topic


on_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}")
))
java
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());
csharp
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}")
}));
go
var onCommitRule Rule
var topic Topic


onCommitRule.AddTarget(targets.NewSnsTopic(topic, &SnsTopicProps{
	Message: events.RuleTargetInput_FromText(
	fmt.Sprintf("A commit was pushed to the repository %v on branch %v", codecommit.ReferenceEvent_RepositoryName(), codecommit.ReferenceEvent_ReferenceName())),
}))

Or using an Object:

ts
declare const onCommitRule: events.Rule;
declare const topic: sns.Topic;

onCommitRule.addTarget(new targets.SnsTopic(topic, {
  message: events.RuleTargetInput.fromObject(
    {
      DataType: `custom_${events.EventField.fromPath('$.detail-type')}`
    }
  )
}));
python
# on_commit_rule: events.Rule
# topic: sns.Topic


on_commit_rule.add_target(targets.SnsTopic(topic,
    message=events.RuleTargetInput.from_object({
        "DataType": f"custom_{events.EventField.fromPath('$.detail-type')}"
    })
))
java
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());
csharp
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')}" }
    })
}));
go
var onCommitRule Rule
var topic Topic


onCommitRule.AddTarget(targets.NewSnsTopic(topic, &SnsTopicProps{
	Message: events.RuleTargetInput_FromObject(map[string]*string{
		"DataType": fmt.Sprintf("custom_%v", events.EventField_fromPath(jsii.String("$.detail-type"))),
	}),
}))

Customizing target input ​

By default a target receives the whole matched event. Use RuleTargetInput to send something else: fromEventPath() sends one part of the event, and fromObject(), fromText() and fromMultilineText() send a value you build. Use EventField inside that value to insert fields from the matched event.

ts
declare const rule: events.Rule;
declare const fn: lambda.Function;

rule.addTarget(new targets.LambdaFunction(fn, {
  event: events.RuleTargetInput.fromObject({
    instance: events.EventField.fromPath('$.detail.instance-id'),
    account: events.EventField.account,
  }),
}));
python
# rule: events.Rule
# fn: lambda.Function


rule.add_target(targets.LambdaFunction(fn,
    event=events.RuleTargetInput.from_object({
        "instance": events.EventField.from_path("$.detail.instance-id"),
        "account": events.EventField.account
    })
))
java
Rule rule;
Function fn;


rule.addTarget(LambdaFunction.Builder.create(fn)
        .event(RuleTargetInput.fromObject(Map.of(
                "instance", EventField.fromPath("$.detail.instance-id"),
                "account", EventField.getAccount())))
        .build());
csharp
Rule rule;
Function fn;


rule.AddTarget(new LambdaFunction(fn, new LambdaFunctionProps {
    Event = RuleTargetInput.FromObject(new Dictionary<string, string> {
        { "instance", EventField.FromPath("$.detail.instance-id") },
        { "account", EventField.Account }
    })
}));
go
var rule Rule
var fn Function


rule.AddTarget(targets.NewLambdaFunction(fn, &LambdaFunctionProps{
	Event: events.RuleTargetInput_FromObject(map[string]*string{
		"instance": events.EventField_fromPath(jsii.String("$.detail.instance-id")),
		"account": events.EventField_account(),
	}),
}))

The prop that takes a RuleTargetInput depends on the target: event on LambdaFunction, message on SnsTopic and SqsQueue.

Role ​

You can specify an IAM Role:

ts
declare const role: iam.IRole;

new events.Rule(this, 'MyRule', {
  schedule: events.Schedule.cron({ minute: '0', hour: '4' }),
  role,
});
python
# role: iam.IRole


events.Rule(self, "MyRule",
    schedule=events.Schedule.cron(minute="0", hour="4"),
    role=role
)
java
IRole role;


Rule.Builder.create(this, "MyRule")
        .schedule(Schedule.cron(CronOptions.builder().minute("0").hour("4").build()))
        .role(role)
        .build();
csharp
IRole role;


new Rule(this, "MyRule", new RuleProps {
    Schedule = Schedule.Cron(new CronOptions { Minute = "0", Hour = "4" }),
    Role = role
});
go
var role IRole


events.NewRule(this, jsii.String("MyRule"), &RuleProps{
	Schedule: events.Schedule_Cron(&CronOptions{
		Minute: jsii.String("0"),
		Hour: jsii.String("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:

ts
const rule = new events.Rule(this, 'rule', {
  eventPattern: {
    detail: {
      object: {
        // Matchers may appear at any level
        size: events.Match.greaterThan(1024),
      },

      // 'OR' condition
      'source-storage-class': events.Match.anyOf(
        events.Match.prefix('GLACIER'),
        events.Match.exactString('DEEP_ARCHIVE'),
      ),
    },

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

    region: events.Match.anythingButPrefix('us-gov'),
  },
});
python
rule = events.Rule(self, "rule",
    event_pattern=events.EventPattern(
        detail={
            "object": {
                # Matchers may appear at any level
                "size": events.Match.greater_than(1024)
            },

            # 'OR' condition
            "source-storage-class": events.Match.any_of(
                events.Match.prefix("GLACIER"),
                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=events.Match.anything_but_prefix("us-gov")
    )
)
java
Rule rule = Rule.Builder.create(this, "rule")
        .eventPattern(EventPattern.builder()
                .detail(Map.of(
                        "object", Map.of(
                                // Matchers may appear at any level
                                "size", Match.greaterThan(1024)),

                        // 'OR' condition
                        "source-storage-class", Match.anyOf(Match.prefix("GLACIER"), Match.exactString("DEEP_ARCHIVE"))))

                // If you prefer, you can use a low level array of strings, as directly consumed by EventBridge
                .source(List.of("aws.s3"))

                .region(Match.anythingButPrefix("us-gov"))
                .build())
        .build();
csharp
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")) }
        },

        // 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")
    }
});
go
rule := events.NewRule(this, jsii.String("rule"), &RuleProps{
	EventPattern: &EventPattern{
		Detail: map[string]interface{}{
			"object": map[string][]*string{
				// Matchers may appear at any level
				"size": events.Match_greaterThan(jsii.Number(1024)),
			},

			// 'OR' condition
			"source-storage-class": events.Match_anyOf(events.Match_prefix(jsii.String("GLACIER")), events.Match_exactString(jsii.String("DEEP_ARCHIVE"))),
		},

		// If you prefer, you can use a low level array of strings, as directly consumed by EventBridge
		Source: []*string{
			jsii.String("aws.s3"),
		},

		Region: events.Match_AnythingButPrefix(jsii.String("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:

ts
const rule = new events.Rule(this, 'rule', {
  eventPattern: {
    detail: {
      bucket: {
        name: events.Match.prefixEqualsIgnoreCase('raw-'),
      },

      object: {
        key: events.Match.wildcard('path/to/object/*.txt'),
      },

      requester: events.Match.suffixEqualsIgnoreCase('.AMAZONAWS.COM'),
    },
    detailType: events.Match.equalsIgnoreCase('object created'),
  },
});
python
rule = events.Rule(self, "rule",
    event_pattern=events.EventPattern(
        detail={
            "bucket": {
                "name": events.Match.prefix_equals_ignore_case("raw-")
            },

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

            "requester": events.Match.suffix_equals_ignore_case(".AMAZONAWS.COM")
        },
        detail_type=events.Match.equals_ignore_case("object created")
    )
)
java
Rule rule = Rule.Builder.create(this, "rule")
        .eventPattern(EventPattern.builder()
                .detail(Map.of(
                        "bucket", Map.of(
                                "name", Match.prefixEqualsIgnoreCase("raw-")),

                        "object", Map.of(
                                "key", Match.wildcard("path/to/object/*.txt")),

                        "requester", Match.suffixEqualsIgnoreCase(".AMAZONAWS.COM")))
                .detailType(Match.equalsIgnoreCase("object created"))
                .build())
        .build();
csharp
var rule = new Rule(this, "rule", new RuleProps {
    EventPattern = new EventPattern {
        Detail = new Dictionary<string, object> {
            { "bucket", new Dictionary<string, string[]> {
                { "name", Match.PrefixEqualsIgnoreCase("raw-") }
            } },

            { "object", new Dictionary<string, string[]> {
                { "key", Match.Wildcard("path/to/object/*.txt") }
            } },

            { "requester", Match.SuffixEqualsIgnoreCase(".AMAZONAWS.COM") }
        },
        DetailType = Match.EqualsIgnoreCase("object created")
    }
});
go
rule := events.NewRule(this, jsii.String("rule"), &RuleProps{
	EventPattern: &EventPattern{
		Detail: map[string]interface{}{
			"bucket": map[string][]*string{
				"name": events.Match_prefixEqualsIgnoreCase(jsii.String("raw-")),
			},

			"object": map[string][]*string{
				"key": events.Match_wildcard(jsii.String("path/to/object/*.txt")),
			},

			"requester": events.Match_suffixEqualsIgnoreCase(jsii.String(".AMAZONAWS.COM")),
		},
		DetailType: events.Match_EqualsIgnoreCase(jsii.String("object created")),
	},
})

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

ts
const rule = new events.Rule(this, 'rule', {
  eventPattern: {
    region: events.Match.anythingBut('us-east-1', 'us-east-2', 'us-west-1', 'us-west-2'),

    detail: {
      bucket: {
        name: events.Match.anythingButPrefix('foo', 'bar', 'baz'),
      },

      object: {
        key: events.Match.anythingButSuffix('.gif', '.png', '.jpg'),
      },

      requester: events.Match.anythingButWildcard('*.amazonaws.com', '123456789012'),
    },
    detailType: events.Match.anythingButEqualsIgnoreCase('object created', 'object deleted'),
  },
});
python
rule = events.Rule(self, "rule",
    event_pattern=events.EventPattern(
        region=events.Match.anything_but("us-east-1", "us-east-2", "us-west-1", "us-west-2"),

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

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

            "requester": events.Match.anything_but_wildcard("*.amazonaws.com", "123456789012")
        },
        detail_type=events.Match.anything_but_equals_ignore_case("object created", "object deleted")
    )
)
java
Rule rule = Rule.Builder.create(this, "rule")
        .eventPattern(EventPattern.builder()
                .region(Match.anythingBut("us-east-1", "us-east-2", "us-west-1", "us-west-2"))

                .detail(Map.of(
                        "bucket", Map.of(
                                "name", Match.anythingButPrefix("foo", "bar", "baz")),

                        "object", Map.of(
                                "key", Match.anythingButSuffix(".gif", ".png", ".jpg")),

                        "requester", Match.anythingButWildcard("*.amazonaws.com", "123456789012")))
                .detailType(Match.anythingButEqualsIgnoreCase("object created", "object deleted"))
                .build())
        .build();
csharp
var rule = new Rule(this, "rule", new RuleProps {
    EventPattern = new EventPattern {
        Region = Match.AnythingBut("us-east-1", "us-east-2", "us-west-1", "us-west-2"),

        Detail = new Dictionary<string, object> {
            { "bucket", new Dictionary<string, string[]> {
                { "name", Match.AnythingButPrefix("foo", "bar", "baz") }
            } },

            { "object", new Dictionary<string, string[]> {
                { "key", Match.AnythingButSuffix(".gif", ".png", ".jpg") }
            } },

            { "requester", Match.AnythingButWildcard("*.amazonaws.com", "123456789012") }
        },
        DetailType = Match.AnythingButEqualsIgnoreCase("object created", "object deleted")
    }
});
go
rule := events.NewRule(this, jsii.String("rule"), &RuleProps{
	EventPattern: &EventPattern{
		Region: events.Match_AnythingBut(jsii.String("us-east-1"), jsii.String("us-east-2"), jsii.String("us-west-1"), jsii.String("us-west-2")),

		Detail: map[string]interface{}{
			"bucket": map[string][]*string{
				"name": events.Match_anythingButPrefix(jsii.String("foo"), jsii.String("bar"), jsii.String("baz")),
			},

			"object": map[string][]*string{
				"key": events.Match_anythingButSuffix(jsii.String(".gif"), jsii.String(".png"), jsii.String(".jpg")),
			},

			"requester": events.Match_anythingButWildcard(jsii.String("*.amazonaws.com"), jsii.String("123456789012")),
		},
		DetailType: events.Match_AnythingButEqualsIgnoreCase(jsii.String("object created"), jsii.String("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:

ts
import { Rule, Schedule } from 'aws-cdk-lib/aws-events';
import { EcsTask } from 'aws-cdk-lib/aws-events-targets';
import { Cluster, TaskDefinition } from 'aws-cdk-lib/aws-ecs';
import { Role } from 'aws-cdk-lib/aws-iam';

declare const cluster: Cluster;
declare const taskDefinition: TaskDefinition;
declare const role: Role;

const ecsTaskTarget = new EcsTask({ cluster, taskDefinition, role });

new Rule(this, 'ScheduleRule', {
 schedule: Schedule.cron({ minute: '0', hour: '4' }),
 targets: [ecsTaskTarget],
});
python
from aws_cdk.aws_events import Rule, Schedule
from aws_cdk.aws_events_targets import EcsTask
from aws_cdk.aws_ecs import Cluster, TaskDefinition
from aws_cdk.aws_iam import Role

# cluster: Cluster
# task_definition: TaskDefinition
# role: Role


ecs_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]
)
java
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();
csharp
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 }
});
go
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"

var cluster Cluster
var taskDefinition TaskDefinition
var role Role


ecsTaskTarget := awscdk.NewEcsTask(&EcsTaskProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	Role: Role,
})

awscdk.NewRule(this, jsii.String("ScheduleRule"), &RuleProps{
	Schedule: awscdk.Schedule_Cron(&CronOptions{
		Minute: jsii.String("0"),
		Hour: jsii.String("4"),
	}),
	Targets: []IRuleTarget{
		ecsTaskTarget,
	},
})

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

ts
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;
declare const role: iam.Role;

const platformVersion = ecs.FargatePlatformVersion.VERSION1_4;
const ecsTaskTarget = new targets.EcsTask({ cluster, taskDefinition, role, platformVersion });
python
# cluster: ecs.Cluster
# task_definition: ecs.TaskDefinition
# role: iam.Role


platform_version = ecs.FargatePlatformVersion.VERSION1_4
ecs_task_target = targets.EcsTask(cluster=cluster, task_definition=task_definition, role=role, platform_version=platform_version)
java
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();
csharp
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 });
go
var cluster Cluster
var taskDefinition TaskDefinition
var role Role


platformVersion := ecs.FargatePlatformVersion_VERSION1_4
ecsTaskTarget := targets.NewEcsTask(&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:

ts
import { App, Stack } from 'aws-cdk-lib';
import * as codebuild from 'aws-cdk-lib/aws-codebuild';
import * as codecommit from 'aws-cdk-lib/aws-codecommit';
import * as targets from 'aws-cdk-lib/aws-events-targets';

const app = new App();

const account1 = '11111111111';
const account2 = '22222222222';

const stack1 = new Stack(app, 'Stack1', { env: { account: account1, region: 'us-west-1' } });
const repo = new codecommit.Repository(stack1, 'Repository', {
  repositoryName: 'myrepository',
});

const stack2 = new Stack(app, 'Stack2', { env: { account: account2, region: 'us-east-1' } });
const project = new codebuild.Project(stack2, 'Project', {
  // ...
});

repo.onCommit('OnCommit', {
  target: new targets.CodeBuildProject(project),
});
python
from aws_cdk import Environment, Environment
from aws_cdk import App, Stack
import aws_cdk.aws_codebuild as codebuild
import aws_cdk.aws_codecommit as codecommit
import aws_cdk.aws_events_targets as targets

app = 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)
)
java
import software.amazon.awscdk.App;
import software.amazon.awscdk.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());
csharp
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)
});
go
import "github.com/aws/aws-cdk-go/awscdk"
import codebuild "github.com/aws/aws-cdk-go/awscdk"
import codecommit "github.com/aws/aws-cdk-go/awscdk"
import targets "github.com/aws/aws-cdk-go/awscdk"

app := awscdk.NewApp()

account1 := "11111111111"
account2 := "22222222222"

stack1 := awscdk.NewStack(app, jsii.String("Stack1"), &StackProps{
	Env: &Environment{
		Account: account1,
		Region: jsii.String("us-west-1"),
	},
})
repo := codecommit.NewRepository(stack1, jsii.String("Repository"), &RepositoryProps{
	RepositoryName: jsii.String("myrepository"),
})

stack2 := awscdk.NewStack(app, jsii.String("Stack2"), &StackProps{
	Env: &Environment{
		Account: account2,
		Region: jsii.String("us-east-1"),
	},
})
project := codebuild.NewProject(stack2, jsii.String("Project"), &ProjectProps{
})

repo.onCommit(jsii.String("OnCommit"), &OnCommitOptions{
	Target: targets.NewCodeBuildProject(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 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.

ts
const bus = new events.EventBus(this, 'bus', {
  eventBusName: 'MyCustomEventBus',
  description: 'MyCustomEventBus',
});

bus.archive('MyArchive', {
  archiveName: 'MyCustomEventBusArchive',
  description: 'MyCustomerEventBus Archive',
  eventPattern: {
    account: [Stack.of(this).account],
  },
  retention: Duration.days(365),
});
python
bus = events.EventBus(self, "bus",
    event_bus_name="MyCustomEventBus",
    description="MyCustomEventBus"
)

bus.archive("MyArchive",
    archive_name="MyCustomEventBusArchive",
    description="MyCustomerEventBus Archive",
    event_pattern=events.EventPattern(
        account=[Stack.of(self).account]
    ),
    retention=Duration.days(365)
)
java
EventBus bus = EventBus.Builder.create(this, "bus")
        .eventBusName("MyCustomEventBus")
        .description("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());
csharp
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)
});
go
bus := events.NewEventBus(this, jsii.String("bus"), &EventBusProps{
	EventBusName: jsii.String("MyCustomEventBus"),
	Description: jsii.String("MyCustomEventBus"),
})

bus.archive(jsii.String("MyArchive"), &BaseArchiveProps{
	ArchiveName: jsii.String("MyCustomEventBusArchive"),
	Description: jsii.String("MyCustomerEventBus Archive"),
	EventPattern: &EventPattern{
		Account: []*string{
			awscdk.*stack_Of(this).Account,
		},
	},
	Retention: awscdk.Duration_Days(jsii.Number(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.

ts
import * as sqs from 'aws-cdk-lib/aws-sqs';

const dlq = new sqs.Queue(this, 'DLQ');

const bus = new events.EventBus(this, 'Bus', {
  deadLetterQueue: dlq,
});
python
import aws_cdk.aws_sqs as sqs


dlq = sqs.Queue(self, "DLQ")

bus = events.EventBus(self, "Bus",
    dead_letter_queue=dlq
)
java
import software.amazon.awscdk.services.sqs.*;


Queue dlq = new Queue(this, "DLQ");

EventBus bus = EventBus.Builder.create(this, "Bus")
        .deadLetterQueue(dlq)
        .build();
csharp
using Amazon.CDK.AWS.SQS;


var dlq = new Queue(this, "DLQ");

var bus = new EventBus(this, "Bus", new EventBusProps {
    DeadLetterQueue = dlq
});
go
import sqs "github.com/aws/aws-cdk-go/awscdk"


dlq := sqs.NewQueue(this, jsii.String("DLQ"))

bus := events.NewEventBus(this, jsii.String("Bus"), &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.

ts
declare const lambdaFunction: lambda.Function;

const eventBus = events.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);
python
# lambda_function: lambda.Function


event_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 eventbus
event_bus.grant_put_events_to(lambda_function)
java
Function 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);
csharp
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);
go
var lambdaFunction Function


eventBus := events.EventBus_FromEventBusArn(this, jsii.String("ImportedEventBus"), jsii.String("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.

ts
import * as kms from 'aws-cdk-lib/aws-kms';

declare const kmsKey: kms.IKey;

new events.EventBus(this, 'Bus', {
  kmsKey,
});
python
import aws_cdk.aws_kms as kms

# kms_key: kms.IKey


events.EventBus(self, "Bus",
    kms_key=kms_key
)
java
import software.amazon.awscdk.services.kms.*;

IKey kmsKey;


EventBus.Builder.create(this, "Bus")
        .kmsKey(kmsKey)
        .build();
csharp
using Amazon.CDK.AWS.KMS;

IKey kmsKey;


new EventBus(this, "Bus", new EventBusProps {
    KmsKey = kmsKey
});
go
import kms "github.com/aws/aws-cdk-go/awscdk"

var kmsKey IKey


events.NewEventBus(this, jsii.String("Bus"), &EventBusProps{
	KmsKey: KmsKey,
})

To use a customer managed key for an archive, use the kmsKey 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.

ts
import * as kms from 'aws-cdk-lib/aws-kms';
import { Archive, EventBus } from 'aws-cdk-lib/aws-events';

const stack = new Stack();

declare const kmsKey: kms.IKey;

const eventBus = new EventBus(stack, 'Bus');

const archive = new Archive(stack, 'Archive', {
  kmsKey: kmsKey,
  sourceEventBus: eventBus,
  eventPattern: {
    source: ['aws.ec2']
  },
});
python
import aws_cdk.aws_kms as kms
from aws_cdk.aws_events import Archive, EventBus

# kms_key: kms.IKey


stack = Stack()

event_bus = EventBus(stack, "Bus")

archive = Archive(stack, "Archive",
    kms_key=kms_key,
    source_event_bus=event_bus,
    event_pattern=events.EventPattern(
        source=["aws.ec2"]
    )
)
java
import software.amazon.awscdk.services.kms.*;
import software.amazon.awscdk.services.events.Archive;
import software.amazon.awscdk.services.events.EventBus;

IKey kmsKey;


Stack stack = new Stack();

EventBus eventBus = new EventBus(stack, "Bus");

Archive archive = Archive.Builder.create(stack, "Archive")
        .kmsKey(kmsKey)
        .sourceEventBus(eventBus)
        .eventPattern(EventPattern.builder()
                .source(List.of("aws.ec2"))
                .build())
        .build();
csharp
using Amazon.CDK.AWS.KMS;
using Amazon.CDK.AWS.Events;

IKey kmsKey;


var stack = new Stack();

var eventBus = new EventBus(stack, "Bus");

var archive = new Archive(stack, "Archive", new ArchiveProps {
    KmsKey = kmsKey,
    SourceEventBus = eventBus,
    EventPattern = new EventPattern {
        Source = new [] { "aws.ec2" }
    }
});
go
import kms "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"

var kmsKey IKey


stack := awscdk.Newstack()

eventBus := awscdk.NewEventBus(stack, jsii.String("Bus"))

archive := awscdk.NewArchive(stack, jsii.String("Archive"), &ArchiveProps{
	KmsKey: kmsKey,
	SourceEventBus: eventBus,
	EventPattern: &EventPattern{
		Source: []*string{
			jsii.String("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.

ts
import { EventBus, IncludeDetail, Level } from 'aws-cdk-lib/aws-events';

const bus =  new EventBus(this, 'Bus', {
      logConfig: {
        includeDetail: IncludeDetail.FULL,
        level: Level.TRACE,
      },
    });
python
from aws_cdk.aws_events import EventBus, IncludeDetail, Level


bus = EventBus(self, "Bus",
    log_config=events.LogConfig(
        include_detail=IncludeDetail.FULL,
        level=Level.TRACE
    )
)
java
import software.amazon.awscdk.services.events.EventBus;
import software.amazon.awscdk.services.events.IncludeDetail;
import software.amazon.awscdk.services.events.Level;


EventBus bus = EventBus.Builder.create(this, "Bus")
        .logConfig(LogConfig.builder()
                .includeDetail(IncludeDetail.FULL)
                .level(Level.TRACE)
                .build())
        .build();
csharp
using Amazon.CDK.AWS.Events;


var bus = new EventBus(this, "Bus", new EventBusProps {
    LogConfig = new LogConfig {
        IncludeDetail = IncludeDetail.FULL,
        Level = Level.TRACE
    }
});
go
import "github.com/aws/aws-cdk-go/awscdk"


bus := awscdk.NewEventBus(this, jsii.String("Bus"), &EventBusProps{
	LogConfig: &LogConfig{
		IncludeDetail: awscdk.IncludeDetail_FULL,
		Level: awscdk.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

Types ​

NameKindSummary
ApiDestinationConstruct (L2)Define an EventBridge Api Destination.
ArchiveConstruct (L2)Define an EventBridge Archive.
ConnectionConstruct (L2)Define an EventBridge Connection.
EventBusConstruct (L2)Define an EventBridge EventBus.
EventBusPolicyConstruct (L2)The policy for an Event Bus.
RuleConstruct (L2)Defines an EventBridge Rule in this stack.
CfnApiDestinationConstruct (L1)Creates an API destination, which is an HTTP invocation endpoint configured as a target for events.
CfnArchiveConstruct (L1)Creates an archive of events with the specified settings.
CfnConnectionConstruct (L1)Creates a connection.
CfnEndpointConstruct (L1)A global endpoint used to improve your application's availability by making it regional-fault tolerant.
CfnEventBusConstruct (L1)Specifies an event bus within your account.
CfnEventBusPolicyConstruct (L1)Running PutPermission permits the specified AWS account or AWS organization to put events to the specified event bus .
CfnRuleConstruct (L1)Creates or updates the specified rule.
ApiDestinationAttributesStructThe properties to import an existing Api Destination.
ApiDestinationPropsStructThe event API Destination properties.
ArchivePropsStructThe event archive properties.
AuthorizationClassAuthorization type for an API Destination Connection.
BaseArchivePropsStructThe event archive base properties.
CfnApiDestinationPropsStructProperties for defining a CfnApiDestination.
CfnArchivePropsStructProperties for defining a CfnArchive.
CfnConnection.ApiKeyAuthParametersPropertyStructThe API key authorization parameters for the connection.
CfnConnection.AuthParametersPropertyStructTthe authorization parameters to use for the connection.
CfnConnection.BasicAuthParametersPropertyStructThe Basic authorization parameters for the connection.
CfnConnection.ClientParametersPropertyStructThe OAuth authorization parameters to use for the connection.
CfnConnection.ConnectionHttpParametersPropertyStructAny additional parameters for the connection.
CfnConnection.ConnectivityParametersPropertyStructIf you specify a private OAuth endpoint, the parameters for EventBridge to use when authenticating against the endpoint.
CfnConnection.InvocationConnectivityParametersPropertyStructFor connections to private APIs, the parameters to use for invoking the API.
CfnConnection.OAuthParametersPropertyStructContains the OAuth authorization parameters to use for the connection.
CfnConnection.ParameterPropertyStructAny additional query string parameter for the connection.
CfnConnection.ResourceParametersPropertyStructThe parameters for EventBridge to use when invoking the resource endpoint.
CfnConnectionPropsStructProperties for defining a CfnConnection.
CfnEndpoint.EndpointEventBusPropertyStructThe event buses the endpoint is associated with.
CfnEndpoint.FailoverConfigPropertyStructThe failover configuration for an endpoint.
CfnEndpoint.PrimaryPropertyStructThe primary Region of the endpoint.
CfnEndpoint.ReplicationConfigPropertyStructEndpoints can replicate all events to the secondary Region.
CfnEndpoint.RoutingConfigPropertyStructThe routing configuration of the endpoint.
CfnEndpoint.SecondaryPropertyStructThe secondary Region that processes events when failover is triggered or replication is enabled.
CfnEndpointPropsStructProperties for defining a CfnEndpoint.
CfnEventBus.DeadLetterConfigPropertyStructConfiguration details of the Amazon SQS queue for EventBridge to use as a dead-letter queue (DLQ).
CfnEventBus.LogConfigPropertyStructThe logging configuration settings for the event bus.
CfnEventBusPolicy.ConditionPropertyStructThis parameter enables you to limit the permission to accounts that fulfill a certain condition, such as being a member of a certain AWS organization.
CfnEventBusPolicyPropsStructProperties for defining a CfnEventBusPolicy.
CfnEventBusPropsStructProperties for defining a CfnEventBus.
CfnRule.AppSyncParametersPropertyStructContains the GraphQL operation to be parsed and executed, if the event target is an AWS AppSync API.
CfnRule.AwsVpcConfigurationPropertyStructThis structure specifies the VPC subnets and security groups for the task, and whether a public IP address is to be used.
CfnRule.BatchArrayPropertiesPropertyStructThe array properties for the submitted job, such as the size of the array.
CfnRule.BatchParametersPropertyStructThe custom parameters to be used when the target is an AWS Batch job.
CfnRule.BatchRetryStrategyPropertyStructThe retry strategy to use for failed jobs, if the target is an AWS Batch job.
CfnRule.CapacityProviderStrategyItemPropertyStructThe details of a capacity provider strategy.
CfnRule.DeadLetterConfigPropertyStructConfiguration details of the Amazon SQS queue for EventBridge to use as a dead-letter queue (DLQ).
CfnRule.EcsParametersPropertyStructThe custom parameters to be used when the target is an Amazon ECS task.
CfnRule.HttpParametersPropertyStructThese are custom parameter to be used when the target is an API Gateway APIs or EventBridge ApiDestinations.
CfnRule.InputTransformerPropertyStructContains 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.KinesisParametersPropertyStructThis 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.NetworkConfigurationPropertyStructThis structure specifies the network configuration for an ECS task.
CfnRule.PlacementConstraintPropertyStructAn object representing a constraint on task placement.
CfnRule.PlacementStrategyPropertyStructThe task placement strategy for a task or service.
CfnRule.RedshiftDataParametersPropertyStructThese 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.RetryPolicyPropertyStructA RetryPolicy object that includes information about the retry policy settings.
CfnRule.RunCommandParametersPropertyStructThis parameter contains the criteria (either InstanceIds or a tag) used to specify which EC2 instances are to be sent the command.
CfnRule.RunCommandTargetPropertyStructInformation about the EC2 instances that are to be sent the command, specified as key-value pairs.
CfnRule.SageMakerPipelineParameterPropertyStructName/Value pair of a parameter to start execution of a SageMaker AI Model Building Pipeline.
CfnRule.SageMakerPipelineParametersPropertyStructThese are custom parameters to use when the target is a SageMaker AI Model Building Pipeline that starts based on EventBridge events.
CfnRule.SqsParametersPropertyStructThe custom parameters for EventBridge to use for a target that is an Amazon SQS fair or FIFO queue.
CfnRule.TagPropertyStructA key-value pair associated with an ECS Target of an EventBridge rule.
CfnRule.TargetPropertyStructTargets are the resources to be invoked when a rule is triggered.
CfnRulePropsStructProperties for defining a CfnRule.
ConnectionAttributesStructInterface with properties necessary to import a reusable Connection.
ConnectionPropsStructAn API Destination Connection.
CronOptionsStructOptions to configure a cron expression.
EventBusAttributesStructInterface with properties necessary to import a reusable EventBus.
EventBusGrantsFacadeCollection of grant methods for a IEventBusRef.
EventBusPolicyPropsStructProperties to associate Event Buses with a policy.
EventBusPropsStructProperties to define an event bus.
EventCommonOptionsStructCommon options for Events.
EventFieldClassRepresents a field in the event pattern.
EventPatternStructEvents in Amazon CloudWatch Events are represented as JSON objects. For more information about JSON objects, see RFC 7159.
HttpMethodEnumSupported HTTP operations.
HttpParameterClassAn additional HTTP parameter to send along with the OAuth request.
IApiDestinationInterfaceInterface for API Destinations.
IConnectionInterfaceInterface for EventBus Connections.
IEventBusInterfaceInterface which all EventBus based classes MUST implement.
IncludeDetailEnumWhether EventBridge include detailed event information in the records it generates.
IRuleInterfaceRepresents an EventBridge Rule.
IRuleTargetInterfaceAn abstract target for EventRules.
LevelEnumThe level of logging detail to include.
LogConfigStructInterface for Logging Configuration of the Event Bus.
MatchClassAn event pattern matcher.
OAuthAuthorizationPropsStructProperties for Authorization.oauth().
OnEventOptionsStructStandard set of options for onXxx event handlers on construct.
RulePropsStructProperties for defining an EventBridge Rule.
RuleTargetConfigStructProperties for an event rule target.
RuleTargetInputClassThe input to send to the event target.
RuleTargetInputPropertiesStructThe input properties for an event target.
ScheduleClassSchedule for scheduled event rules.