# Amazon EventBridge Construct Library
<!--BEGIN STABILITY BANNER-->---
![cfn-resources: Stable](https://img.shields.io/badge/cfn--resources-stable-success.svg?style=for-the-badge)
![cdk-constructs: Stable](https://img.shields.io/badge/cdk--constructs-stable-success.svg?style=for-the-badge)
---
<!--END STABILITY BANNER-->
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](https://docs.aws.amazon.com/eventbridge/latest/userguide/event-types.html#codepipeline-event-type)
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](https://docs.aws.amazon.com/eventbridge/latest/userguide/event-types.html).
* **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](https://docs.aws.amazon.com/eventbridge/latest/userguide/create-event-bus.html).
## Rule
The `Rule` construct defines an EventBridge rule which monitors an
event based on an [event
pattern](https://docs.aws.amazon.com/eventbridge/latest/userguide/filtering-examples-structure.html)
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:
```python
# repo: codecommit.Repository
# project: codebuild.Project
on_commit_rule = repo.on_commit("OnCommit",
target=targets.CodeBuildProject(project),
branches=["master"]
)
```
You can add additional targets, with optional [input
transformer](https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_InputTransformer.html)
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:
```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}")
))
```
Or using an Object:
```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')}"
})
))
```
## 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:
```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]
)
```
If you want to specify Fargate platform version, set `platformVersion` in EcsTask's props like the following example:
```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)
```
## 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 build
* `targets.CodePipeline`: Start an AWS CodePipeline pipeline execution
* `targets.EcsTask`: Start a task on an Amazon ECS cluster
* `targets.LambdaFunction`: Invoke an AWS Lambda function
* `targets.SnsTopic`: Publish into an SNS topic
* `targets.SqsQueue`: Send a message to an Amazon SQS Queue
* `targets.SfnStateMachine`: Trigger an AWS Step Functions state machine
* `targets.BatchJob`: Queue an AWS Batch Job
* `targets.AwsApi`: Make an AWS API call
* `targets.ApiGateway`: Invoke an AWS API Gateway
* `targets.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:
```python
from aws_cdk.core import Environment, Environment
from aws_cdk.core 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)
)
```
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](https://docs.aws.amazon.com/eventbridge/latest/userguide/eventbridge-cross-account-event-delivery.html).
## Archiving
It is possible to archive all or some events sent to an event bus. It is then possible to [replay these events](https://aws.amazon.com/blogs/aws/new-archive-and-replay-events-with-amazon-eventbridge/).
```python
bus = events.EventBus(self, "bus",
event_bus_name="MyCustomEventBus"
)
bus.archive("MyArchive",
archive_name="MyCustomEventBusArchive",
description="MyCustomerEventBus Archive",
event_pattern=events.EventPattern(
account=[Stack.of(self).account]
),
retention=Duration.days(365)
)
```
## Granting PutEvents to an existing 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.
```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)
```
Raw data
{
"_id": null,
"home_page": "https://github.com/aws/aws-cdk",
"name": "aws-cdk.aws-events",
"maintainer": "",
"docs_url": null,
"requires_python": "~=3.7",
"maintainer_email": "",
"keywords": "",
"author": "Amazon Web Services",
"author_email": "",
"download_url": "",
"platform": null,
"description": "# Amazon EventBridge Construct Library\n\n<!--BEGIN STABILITY BANNER-->---\n\n\n![cfn-resources: Stable](https://img.shields.io/badge/cfn--resources-stable-success.svg?style=for-the-badge)\n\n![cdk-constructs: Stable](https://img.shields.io/badge/cdk--constructs-stable-success.svg?style=for-the-badge)\n\n---\n<!--END STABILITY BANNER-->\n\nAmazon EventBridge delivers a near real-time stream of system events that\ndescribe changes in AWS resources. For example, an AWS CodePipeline emits the\n[State\nChange](https://docs.aws.amazon.com/eventbridge/latest/userguide/event-types.html#codepipeline-event-type)\nevent when the pipeline changes its state.\n\n* **Events**: An event indicates a change in your AWS environment. AWS resources\n can generate events when their state changes. For example, Amazon EC2\n generates an event when the state of an EC2 instance changes from pending to\n running, and Amazon EC2 Auto Scaling generates events when it launches or\n terminates instances. AWS CloudTrail publishes events when you make API calls.\n You can generate custom application-level events and publish them to\n EventBridge. You can also set up scheduled events that are generated on\n a periodic basis. For a list of services that generate events, and sample\n events from each service, see [EventBridge Event Examples From Each\n Supported\n Service](https://docs.aws.amazon.com/eventbridge/latest/userguide/event-types.html).\n* **Targets**: A target processes events. Targets can include Amazon EC2\n instances, AWS Lambda functions, Kinesis streams, Amazon ECS tasks, Step\n Functions state machines, Amazon SNS topics, Amazon SQS queues, Amazon CloudWatch LogGroups, and built-in\n targets. A target receives events in JSON format.\n* **Rules**: A rule matches incoming events and routes them to targets for\n processing. A single rule can route to multiple targets, all of which are\n processed in parallel. Rules are not processed in a particular order. This\n enables different parts of an organization to look for and process the events\n that are of interest to them. A rule can customize the JSON sent to the\n target, by passing only certain parts or by overwriting it with a constant.\n* **EventBuses**: An event bus can receive events from your own custom applications\n or it can receive events from applications and services created by AWS SaaS partners.\n See [Creating an Event Bus](https://docs.aws.amazon.com/eventbridge/latest/userguide/create-event-bus.html).\n\n## Rule\n\nThe `Rule` construct defines an EventBridge rule which monitors an\nevent based on an [event\npattern](https://docs.aws.amazon.com/eventbridge/latest/userguide/filtering-examples-structure.html)\nand invoke **event targets** when the pattern is matched against a triggered\nevent. Event targets are objects that implement the `IRuleTarget` interface.\n\nNormally, you will use one of the `source.onXxx(name[, target[, options]]) -> Rule` methods on the event source to define an event rule associated with\nthe specific activity. You can targets either via props, or add targets using\n`rule.addTarget`.\n\nFor example, to define an rule that triggers a CodeBuild project build when a\ncommit is pushed to the \"master\" branch of a CodeCommit repository:\n\n```python\n# repo: codecommit.Repository\n# project: codebuild.Project\n\n\non_commit_rule = repo.on_commit(\"OnCommit\",\n target=targets.CodeBuildProject(project),\n branches=[\"master\"]\n)\n```\n\nYou can add additional targets, with optional [input\ntransformer](https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_InputTransformer.html)\nusing `eventRule.addTarget(target[, input])`. For example, we can add a SNS\ntopic target which formats a human-readable message for the commit.\n\nFor example, this adds an SNS topic as a target:\n\n```python\n# on_commit_rule: events.Rule\n# topic: sns.Topic\n\n\non_commit_rule.add_target(targets.SnsTopic(topic,\n message=events.RuleTargetInput.from_text(f\"A commit was pushed to the repository {codecommit.ReferenceEvent.repositoryName} on branch {codecommit.ReferenceEvent.referenceName}\")\n))\n```\n\nOr using an Object:\n\n```python\n# on_commit_rule: events.Rule\n# topic: sns.Topic\n\n\non_commit_rule.add_target(targets.SnsTopic(topic,\n message=events.RuleTargetInput.from_object({\n \"DataType\": f\"custom_{events.EventField.fromPath('$.detail-type')}\"\n })\n))\n```\n\n## Scheduling\n\nYou can configure a Rule to run on a schedule (cron or rate).\nRate must be specified in minutes, hours or days.\n\nThe following example runs a task every day at 4am:\n\n```python\nfrom aws_cdk.aws_events import Rule, Schedule\nfrom aws_cdk.aws_events_targets import EcsTask\nfrom aws_cdk.aws_ecs import Cluster, TaskDefinition\nfrom aws_cdk.aws_iam import Role\n\n# cluster: Cluster\n# task_definition: TaskDefinition\n# role: Role\n\n\necs_task_target = EcsTask(cluster=cluster, task_definition=task_definition, role=role)\n\nRule(self, \"ScheduleRule\",\n schedule=Schedule.cron(minute=\"0\", hour=\"4\"),\n targets=[ecs_task_target]\n)\n```\n\nIf you want to specify Fargate platform version, set `platformVersion` in EcsTask's props like the following example:\n\n```python\n# cluster: ecs.Cluster\n# task_definition: ecs.TaskDefinition\n# role: iam.Role\n\n\nplatform_version = ecs.FargatePlatformVersion.VERSION1_4\necs_task_target = targets.EcsTask(cluster=cluster, task_definition=task_definition, role=role, platform_version=platform_version)\n```\n\n## Event Targets\n\nThe `@aws-cdk/aws-events-targets` module includes classes that implement the `IRuleTarget`\ninterface for various AWS services.\n\nThe following targets are supported:\n\n* `targets.CodeBuildProject`: Start an AWS CodeBuild build\n* `targets.CodePipeline`: Start an AWS CodePipeline pipeline execution\n* `targets.EcsTask`: Start a task on an Amazon ECS cluster\n* `targets.LambdaFunction`: Invoke an AWS Lambda function\n* `targets.SnsTopic`: Publish into an SNS topic\n* `targets.SqsQueue`: Send a message to an Amazon SQS Queue\n* `targets.SfnStateMachine`: Trigger an AWS Step Functions state machine\n* `targets.BatchJob`: Queue an AWS Batch Job\n* `targets.AwsApi`: Make an AWS API call\n* `targets.ApiGateway`: Invoke an AWS API Gateway\n* `targets.ApiDestination`: Make an call to an external destination\n\n### Cross-account and cross-region targets\n\nIt's possible to have the source of the event and a target in separate AWS accounts and regions:\n\n```python\nfrom aws_cdk.core import Environment, Environment\nfrom aws_cdk.core import App, Stack\nimport aws_cdk.aws_codebuild as codebuild\nimport aws_cdk.aws_codecommit as codecommit\nimport aws_cdk.aws_events_targets as targets\n\napp = App()\n\naccount1 = \"11111111111\"\naccount2 = \"22222222222\"\n\nstack1 = Stack(app, \"Stack1\", env=Environment(account=account1, region=\"us-west-1\"))\nrepo = codecommit.Repository(stack1, \"Repository\",\n repository_name=\"myrepository\"\n)\n\nstack2 = Stack(app, \"Stack2\", env=Environment(account=account2, region=\"us-east-1\"))\nproject = codebuild.Project(stack2, \"Project\")\n\nrepo.on_commit(\"OnCommit\",\n target=targets.CodeBuildProject(project)\n)\n```\n\nIn this situation, the CDK will wire the 2 accounts together:\n\n* It will generate a rule in the source stack with the event bus of the target account as the target\n* It will generate a rule in the target stack, with the provided target\n* It will generate a separate stack that gives the source account permissions to publish events\n to the event bus of the target account in the given region,\n and make sure its deployed before the source stack\n\nFor more information, see the\n[AWS documentation on cross-account events](https://docs.aws.amazon.com/eventbridge/latest/userguide/eventbridge-cross-account-event-delivery.html).\n\n## Archiving\n\nIt is possible to archive all or some events sent to an event bus. It is then possible to [replay these events](https://aws.amazon.com/blogs/aws/new-archive-and-replay-events-with-amazon-eventbridge/).\n\n```python\nbus = events.EventBus(self, \"bus\",\n event_bus_name=\"MyCustomEventBus\"\n)\n\nbus.archive(\"MyArchive\",\n archive_name=\"MyCustomEventBusArchive\",\n description=\"MyCustomerEventBus Archive\",\n event_pattern=events.EventPattern(\n account=[Stack.of(self).account]\n ),\n retention=Duration.days(365)\n)\n```\n\n## Granting PutEvents to an existing EventBus\n\nTo import an existing EventBus into your CDK application, use `EventBus.fromEventBusArn`, `EventBus.fromEventBusAttributes`\nor `EventBus.fromEventBusName` factory method.\n\nThen, you can use the `grantPutEventsTo` method to grant `event:PutEvents` to the eventBus.\n\n```python\n# lambda_function: lambda.Function\n\n\nevent_bus = events.EventBus.from_event_bus_arn(self, \"ImportedEventBus\", \"arn:aws:events:us-east-1:111111111:event-bus/my-event-bus\")\n\n# now you can just call methods on the eventbus\nevent_bus.grant_put_events_to(lambda_function)\n```\n\n\n",
"bugtrack_url": null,
"license": "Apache-2.0",
"summary": "Amazon EventBridge Construct Library",
"version": "1.189.0",
"split_keywords": [],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "1a7b93bdc8e44e05408f1f32d50853400615417198ff313ac5c6dd947e5edd0b",
"md5": "ce419a854fd764674ab170b5df4afa6a",
"sha256": "d8c2af2c392805d8bc8e002b2a55a7bb4352f135bcaf157279a4b1e9f17fd761"
},
"downloads": -1,
"filename": "aws_cdk.aws_events-1.189.0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "ce419a854fd764674ab170b5df4afa6a",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": "~=3.7",
"size": 368780,
"upload_time": "2023-01-19T03:39:39",
"upload_time_iso_8601": "2023-01-19T03:39:39.319472Z",
"url": "https://files.pythonhosted.org/packages/1a/7b/93bdc8e44e05408f1f32d50853400615417198ff313ac5c6dd947e5edd0b/aws_cdk.aws_events-1.189.0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2023-01-19 03:39:39",
"github": true,
"gitlab": false,
"bitbucket": false,
"github_user": "aws",
"github_project": "aws-cdk",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "aws-cdk.aws-events"
}