# Event Targets for Amazon EventBridge
<!--BEGIN STABILITY BANNER-->---
![cdk-constructs: Stable](https://img.shields.io/badge/cdk--constructs-stable-success.svg?style=for-the-badge)
---
<!--END STABILITY BANNER-->
This library contains integration classes to send Amazon EventBridge to any
number of supported AWS Services. Instances of these classes should be passed
to the `rule.addTarget()` method.
Currently supported are:
* [Start a CodeBuild build](#start-a-codebuild-build)
* [Start a CodePipeline pipeline](#start-a-codepipeline-pipeline)
* Run an ECS task
* [Invoke a Lambda function](#invoke-a-lambda-function)
* [Invoke a API Gateway REST API](#invoke-an-api-gateway-rest-api)
* Publish a message to an SNS topic
* Send a message to an SQS queue
* [Start a StepFunctions state machine](#start-a-stepfunctions-state-machine)
* [Queue a Batch job](#queue-a-batch-job)
* Make an AWS API call
* Put a record to a Kinesis stream
* [Log an event into a LogGroup](#log-an-event-into-a-loggroup)
* Put a record to a Kinesis Data Firehose stream
* [Put an event on an EventBridge bus](#put-an-event-on-an-eventbridge-bus)
* [Send an event to EventBridge API Destination](#invoke-an-api-destination)
See the README of the `@aws-cdk/aws-events` library for more information on
EventBridge.
## Event retry policy and using dead-letter queues
The Codebuild, CodePipeline, Lambda, StepFunctions, LogGroup and SQSQueue targets support attaching a [dead letter queue and setting retry policies](https://docs.aws.amazon.com/eventbridge/latest/userguide/rule-dlq.html). See the [lambda example](#invoke-a-lambda-function).
Use [escape hatches](https://docs.aws.amazon.com/cdk/latest/guide/cfn_layer.html) for the other target types.
## Invoke a Lambda function
Use the `LambdaFunction` target to invoke a lambda function.
The code snippet below creates an event rule with a Lambda function as a target
triggered for every events from `aws.ec2` source. You can optionally attach a
[dead letter queue](https://docs.aws.amazon.com/eventbridge/latest/userguide/rule-dlq.html).
```python
import aws_cdk.aws_lambda as lambda_
fn = lambda_.Function(self, "MyFunc",
runtime=lambda_.Runtime.NODEJS_14_X,
handler="index.handler",
code=lambda_.Code.from_inline("exports.handler = handler.toString()")
)
rule = events.Rule(self, "rule",
event_pattern=events.EventPattern(
source=["aws.ec2"]
)
)
queue = sqs.Queue(self, "Queue")
rule.add_target(targets.LambdaFunction(fn,
dead_letter_queue=queue, # Optional: add a dead letter queue
max_event_age=cdk.Duration.hours(2), # Optional: set the maxEventAge retry policy
retry_attempts=2
))
```
## Log an event into a LogGroup
Use the `LogGroup` target to log your events in a CloudWatch LogGroup.
For example, the following code snippet creates an event rule with a CloudWatch LogGroup as a target.
Every events sent from the `aws.ec2` source will be sent to the CloudWatch LogGroup.
```python
import aws_cdk.aws_logs as logs
log_group = logs.LogGroup(self, "MyLogGroup",
log_group_name="MyLogGroup"
)
rule = events.Rule(self, "rule",
event_pattern=events.EventPattern(
source=["aws.ec2"]
)
)
rule.add_target(targets.CloudWatchLogGroup(log_group))
```
## Start a CodeBuild build
Use the `CodeBuildProject` target to trigger a CodeBuild project.
The code snippet below creates a CodeCommit repository that triggers a CodeBuild project
on commit to the master branch. You can optionally attach a
[dead letter queue](https://docs.aws.amazon.com/eventbridge/latest/userguide/rule-dlq.html).
```python
import aws_cdk.aws_codebuild as codebuild
import aws_cdk.aws_codecommit as codecommit
repo = codecommit.Repository(self, "MyRepo",
repository_name="aws-cdk-codebuild-events"
)
project = codebuild.Project(self, "MyProject",
source=codebuild.Source.code_commit(repository=repo)
)
dead_letter_queue = sqs.Queue(self, "DeadLetterQueue")
# trigger a build when a commit is pushed to the repo
on_commit_rule = repo.on_commit("OnCommit",
target=targets.CodeBuildProject(project,
dead_letter_queue=dead_letter_queue
),
branches=["master"]
)
```
## Start a CodePipeline pipeline
Use the `CodePipeline` target to trigger a CodePipeline pipeline.
The code snippet below creates a CodePipeline pipeline that is triggered every hour
```python
import aws_cdk.aws_codepipeline as codepipeline
pipeline = codepipeline.Pipeline(self, "Pipeline")
rule = events.Rule(self, "Rule",
schedule=events.Schedule.expression("rate(1 hour)")
)
rule.add_target(targets.CodePipeline(pipeline))
```
## Start a StepFunctions state machine
Use the `SfnStateMachine` target to trigger a State Machine.
The code snippet below creates a Simple StateMachine that is triggered every minute with a
dummy object as input.
You can optionally attach a
[dead letter queue](https://docs.aws.amazon.com/eventbridge/latest/userguide/rule-dlq.html)
to the target.
```python
import aws_cdk.aws_iam as iam
import aws_cdk.aws_stepfunctions as sfn
rule = events.Rule(self, "Rule",
schedule=events.Schedule.rate(cdk.Duration.minutes(1))
)
dlq = sqs.Queue(self, "DeadLetterQueue")
role = iam.Role(self, "Role",
assumed_by=iam.ServicePrincipal("events.amazonaws.com")
)
state_machine = sfn.StateMachine(self, "SM",
definition=sfn.Wait(self, "Hello", time=sfn.WaitTime.duration(cdk.Duration.seconds(10)))
)
rule.add_target(targets.SfnStateMachine(state_machine,
input=events.RuleTargetInput.from_object({"SomeParam": "SomeValue"}),
dead_letter_queue=dlq,
role=role
))
```
## Queue a Batch job
Use the `BatchJob` target to queue a Batch job.
The code snippet below creates a Simple JobQueue that is triggered every hour with a
dummy object as input.
You can optionally attach a
[dead letter queue](https://docs.aws.amazon.com/eventbridge/latest/userguide/rule-dlq.html)
to the target.
```python
import aws_cdk.aws_batch as batch
from aws_cdk.aws_ecs import ContainerImage
job_queue = batch.JobQueue(self, "MyQueue",
compute_environments=[batch.JobQueueComputeEnvironment(
compute_environment=batch.ComputeEnvironment(self, "ComputeEnvironment",
managed=False
),
order=1
)
]
)
job_definition = batch.JobDefinition(self, "MyJob",
container=batch.JobDefinitionContainer(
image=ContainerImage.from_registry("test-repo")
)
)
queue = sqs.Queue(self, "Queue")
rule = events.Rule(self, "Rule",
schedule=events.Schedule.rate(cdk.Duration.hours(1))
)
rule.add_target(targets.BatchJob(job_queue.job_queue_arn, job_queue, job_definition.job_definition_arn, job_definition,
dead_letter_queue=queue,
event=events.RuleTargetInput.from_object({"SomeParam": "SomeValue"}),
retry_attempts=2,
max_event_age=cdk.Duration.hours(2)
))
```
## Invoke an API Gateway REST API
Use the `ApiGateway` target to trigger a REST API.
The code snippet below creates a Api Gateway REST API that is invoked every hour.
```python
import aws_cdk.aws_apigateway as api
import aws_cdk.aws_lambda as lambda_
rule = events.Rule(self, "Rule",
schedule=events.Schedule.rate(cdk.Duration.minutes(1))
)
fn = lambda_.Function(self, "MyFunc",
handler="index.handler",
runtime=lambda_.Runtime.NODEJS_14_X,
code=lambda_.Code.from_inline("exports.handler = e => {}")
)
rest_api = api.LambdaRestApi(self, "MyRestAPI", handler=fn)
dlq = sqs.Queue(self, "DeadLetterQueue")
rule.add_target(
targets.ApiGateway(rest_api,
path="/*/test",
method="GET",
stage="prod",
path_parameter_values=["path-value"],
header_parameters={
"Header1": "header1"
},
query_string_parameters={
"QueryParam1": "query-param-1"
},
dead_letter_queue=dlq
))
```
## Invoke an API Destination
Use the `targets.ApiDestination` target to trigger an external API. You need to
create an `events.Connection` and `events.ApiDestination` as well.
The code snippet below creates an external destination that is invoked every hour.
```python
connection = events.Connection(self, "Connection",
authorization=events.Authorization.api_key("x-api-key", SecretValue.secrets_manager("ApiSecretName")),
description="Connection with API Key x-api-key"
)
destination = events.ApiDestination(self, "Destination",
connection=connection,
endpoint="https://example.com",
description="Calling example.com with API key x-api-key"
)
rule = events.Rule(self, "Rule",
schedule=events.Schedule.rate(cdk.Duration.minutes(1)),
targets=[targets.ApiDestination(destination)]
)
```
## Put an event on an EventBridge bus
Use the `EventBus` target to route event to a different EventBus.
The code snippet below creates the scheduled event rule that route events to an imported event bus.
```python
rule = events.Rule(self, "Rule",
schedule=events.Schedule.expression("rate(1 minute)")
)
rule.add_target(targets.EventBus(
events.EventBus.from_event_bus_arn(self, "External", "arn:aws:events:eu-west-1:999999999999:event-bus/test-bus")))
```
Raw data
{
"_id": null,
"home_page": "https://github.com/aws/aws-cdk",
"name": "aws-cdk.aws-events-targets",
"maintainer": "",
"docs_url": null,
"requires_python": "~=3.7",
"maintainer_email": "",
"keywords": "",
"author": "Amazon Web Services",
"author_email": "",
"download_url": "",
"platform": null,
"description": "# Event Targets for Amazon EventBridge\n\n<!--BEGIN STABILITY BANNER-->---\n\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\nThis library contains integration classes to send Amazon EventBridge to any\nnumber of supported AWS Services. Instances of these classes should be passed\nto the `rule.addTarget()` method.\n\nCurrently supported are:\n\n* [Start a CodeBuild build](#start-a-codebuild-build)\n* [Start a CodePipeline pipeline](#start-a-codepipeline-pipeline)\n* Run an ECS task\n* [Invoke a Lambda function](#invoke-a-lambda-function)\n* [Invoke a API Gateway REST API](#invoke-an-api-gateway-rest-api)\n* Publish a message to an SNS topic\n* Send a message to an SQS queue\n* [Start a StepFunctions state machine](#start-a-stepfunctions-state-machine)\n* [Queue a Batch job](#queue-a-batch-job)\n* Make an AWS API call\n* Put a record to a Kinesis stream\n* [Log an event into a LogGroup](#log-an-event-into-a-loggroup)\n* Put a record to a Kinesis Data Firehose stream\n* [Put an event on an EventBridge bus](#put-an-event-on-an-eventbridge-bus)\n* [Send an event to EventBridge API Destination](#invoke-an-api-destination)\n\nSee the README of the `@aws-cdk/aws-events` library for more information on\nEventBridge.\n\n## Event retry policy and using dead-letter queues\n\nThe Codebuild, CodePipeline, Lambda, StepFunctions, LogGroup and SQSQueue targets support attaching a [dead letter queue and setting retry policies](https://docs.aws.amazon.com/eventbridge/latest/userguide/rule-dlq.html). See the [lambda example](#invoke-a-lambda-function).\nUse [escape hatches](https://docs.aws.amazon.com/cdk/latest/guide/cfn_layer.html) for the other target types.\n\n## Invoke a Lambda function\n\nUse the `LambdaFunction` target to invoke a lambda function.\n\nThe code snippet below creates an event rule with a Lambda function as a target\ntriggered for every events from `aws.ec2` source. You can optionally attach a\n[dead letter queue](https://docs.aws.amazon.com/eventbridge/latest/userguide/rule-dlq.html).\n\n```python\nimport aws_cdk.aws_lambda as lambda_\n\n\nfn = lambda_.Function(self, \"MyFunc\",\n runtime=lambda_.Runtime.NODEJS_14_X,\n handler=\"index.handler\",\n code=lambda_.Code.from_inline(\"exports.handler = handler.toString()\")\n)\n\nrule = events.Rule(self, \"rule\",\n event_pattern=events.EventPattern(\n source=[\"aws.ec2\"]\n )\n)\n\nqueue = sqs.Queue(self, \"Queue\")\n\nrule.add_target(targets.LambdaFunction(fn,\n dead_letter_queue=queue, # Optional: add a dead letter queue\n max_event_age=cdk.Duration.hours(2), # Optional: set the maxEventAge retry policy\n retry_attempts=2\n))\n```\n\n## Log an event into a LogGroup\n\nUse the `LogGroup` target to log your events in a CloudWatch LogGroup.\n\nFor example, the following code snippet creates an event rule with a CloudWatch LogGroup as a target.\nEvery events sent from the `aws.ec2` source will be sent to the CloudWatch LogGroup.\n\n```python\nimport aws_cdk.aws_logs as logs\n\n\nlog_group = logs.LogGroup(self, \"MyLogGroup\",\n log_group_name=\"MyLogGroup\"\n)\n\nrule = events.Rule(self, \"rule\",\n event_pattern=events.EventPattern(\n source=[\"aws.ec2\"]\n )\n)\n\nrule.add_target(targets.CloudWatchLogGroup(log_group))\n```\n\n## Start a CodeBuild build\n\nUse the `CodeBuildProject` target to trigger a CodeBuild project.\n\nThe code snippet below creates a CodeCommit repository that triggers a CodeBuild project\non commit to the master branch. You can optionally attach a\n[dead letter queue](https://docs.aws.amazon.com/eventbridge/latest/userguide/rule-dlq.html).\n\n```python\nimport aws_cdk.aws_codebuild as codebuild\nimport aws_cdk.aws_codecommit as codecommit\n\n\nrepo = codecommit.Repository(self, \"MyRepo\",\n repository_name=\"aws-cdk-codebuild-events\"\n)\n\nproject = codebuild.Project(self, \"MyProject\",\n source=codebuild.Source.code_commit(repository=repo)\n)\n\ndead_letter_queue = sqs.Queue(self, \"DeadLetterQueue\")\n\n# trigger a build when a commit is pushed to the repo\non_commit_rule = repo.on_commit(\"OnCommit\",\n target=targets.CodeBuildProject(project,\n dead_letter_queue=dead_letter_queue\n ),\n branches=[\"master\"]\n)\n```\n\n## Start a CodePipeline pipeline\n\nUse the `CodePipeline` target to trigger a CodePipeline pipeline.\n\nThe code snippet below creates a CodePipeline pipeline that is triggered every hour\n\n```python\nimport aws_cdk.aws_codepipeline as codepipeline\n\n\npipeline = codepipeline.Pipeline(self, \"Pipeline\")\n\nrule = events.Rule(self, \"Rule\",\n schedule=events.Schedule.expression(\"rate(1 hour)\")\n)\n\nrule.add_target(targets.CodePipeline(pipeline))\n```\n\n## Start a StepFunctions state machine\n\nUse the `SfnStateMachine` target to trigger a State Machine.\n\nThe code snippet below creates a Simple StateMachine that is triggered every minute with a\ndummy object as input.\nYou can optionally attach a\n[dead letter queue](https://docs.aws.amazon.com/eventbridge/latest/userguide/rule-dlq.html)\nto the target.\n\n```python\nimport aws_cdk.aws_iam as iam\nimport aws_cdk.aws_stepfunctions as sfn\n\n\nrule = events.Rule(self, \"Rule\",\n schedule=events.Schedule.rate(cdk.Duration.minutes(1))\n)\n\ndlq = sqs.Queue(self, \"DeadLetterQueue\")\n\nrole = iam.Role(self, \"Role\",\n assumed_by=iam.ServicePrincipal(\"events.amazonaws.com\")\n)\nstate_machine = sfn.StateMachine(self, \"SM\",\n definition=sfn.Wait(self, \"Hello\", time=sfn.WaitTime.duration(cdk.Duration.seconds(10)))\n)\n\nrule.add_target(targets.SfnStateMachine(state_machine,\n input=events.RuleTargetInput.from_object({\"SomeParam\": \"SomeValue\"}),\n dead_letter_queue=dlq,\n role=role\n))\n```\n\n## Queue a Batch job\n\nUse the `BatchJob` target to queue a Batch job.\n\nThe code snippet below creates a Simple JobQueue that is triggered every hour with a\ndummy object as input.\nYou can optionally attach a\n[dead letter queue](https://docs.aws.amazon.com/eventbridge/latest/userguide/rule-dlq.html)\nto the target.\n\n```python\nimport aws_cdk.aws_batch as batch\nfrom aws_cdk.aws_ecs import ContainerImage\n\n\njob_queue = batch.JobQueue(self, \"MyQueue\",\n compute_environments=[batch.JobQueueComputeEnvironment(\n compute_environment=batch.ComputeEnvironment(self, \"ComputeEnvironment\",\n managed=False\n ),\n order=1\n )\n ]\n)\n\njob_definition = batch.JobDefinition(self, \"MyJob\",\n container=batch.JobDefinitionContainer(\n image=ContainerImage.from_registry(\"test-repo\")\n )\n)\n\nqueue = sqs.Queue(self, \"Queue\")\n\nrule = events.Rule(self, \"Rule\",\n schedule=events.Schedule.rate(cdk.Duration.hours(1))\n)\n\nrule.add_target(targets.BatchJob(job_queue.job_queue_arn, job_queue, job_definition.job_definition_arn, job_definition,\n dead_letter_queue=queue,\n event=events.RuleTargetInput.from_object({\"SomeParam\": \"SomeValue\"}),\n retry_attempts=2,\n max_event_age=cdk.Duration.hours(2)\n))\n```\n\n## Invoke an API Gateway REST API\n\nUse the `ApiGateway` target to trigger a REST API.\n\nThe code snippet below creates a Api Gateway REST API that is invoked every hour.\n\n```python\nimport aws_cdk.aws_apigateway as api\nimport aws_cdk.aws_lambda as lambda_\n\n\nrule = events.Rule(self, \"Rule\",\n schedule=events.Schedule.rate(cdk.Duration.minutes(1))\n)\n\nfn = lambda_.Function(self, \"MyFunc\",\n handler=\"index.handler\",\n runtime=lambda_.Runtime.NODEJS_14_X,\n code=lambda_.Code.from_inline(\"exports.handler = e => {}\")\n)\n\nrest_api = api.LambdaRestApi(self, \"MyRestAPI\", handler=fn)\n\ndlq = sqs.Queue(self, \"DeadLetterQueue\")\n\nrule.add_target(\n targets.ApiGateway(rest_api,\n path=\"/*/test\",\n method=\"GET\",\n stage=\"prod\",\n path_parameter_values=[\"path-value\"],\n header_parameters={\n \"Header1\": \"header1\"\n },\n query_string_parameters={\n \"QueryParam1\": \"query-param-1\"\n },\n dead_letter_queue=dlq\n ))\n```\n\n## Invoke an API Destination\n\nUse the `targets.ApiDestination` target to trigger an external API. You need to\ncreate an `events.Connection` and `events.ApiDestination` as well.\n\nThe code snippet below creates an external destination that is invoked every hour.\n\n```python\nconnection = events.Connection(self, \"Connection\",\n authorization=events.Authorization.api_key(\"x-api-key\", SecretValue.secrets_manager(\"ApiSecretName\")),\n description=\"Connection with API Key x-api-key\"\n)\n\ndestination = events.ApiDestination(self, \"Destination\",\n connection=connection,\n endpoint=\"https://example.com\",\n description=\"Calling example.com with API key x-api-key\"\n)\n\nrule = events.Rule(self, \"Rule\",\n schedule=events.Schedule.rate(cdk.Duration.minutes(1)),\n targets=[targets.ApiDestination(destination)]\n)\n```\n\n## Put an event on an EventBridge bus\n\nUse the `EventBus` target to route event to a different EventBus.\n\nThe code snippet below creates the scheduled event rule that route events to an imported event bus.\n\n```python\nrule = events.Rule(self, \"Rule\",\n schedule=events.Schedule.expression(\"rate(1 minute)\")\n)\n\nrule.add_target(targets.EventBus(\n events.EventBus.from_event_bus_arn(self, \"External\", \"arn:aws:events:eu-west-1:999999999999:event-bus/test-bus\")))\n```\n\n\n",
"bugtrack_url": null,
"license": "Apache-2.0",
"summary": "Event targets for Amazon EventBridge",
"version": "1.189.0",
"split_keywords": [],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "bebfa26b2934450b24485221f556aba7162a91b6963d56eb0d35fc77b90eda01",
"md5": "4784b01bb08f972096d91fbd18c30fce",
"sha256": "b096ea0c119991ad992e5fd46d759d1a49b0984f167dcd9d58554282220f8c5e"
},
"downloads": -1,
"filename": "aws_cdk.aws_events_targets-1.189.0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "4784b01bb08f972096d91fbd18c30fce",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": "~=3.7",
"size": 151856,
"upload_time": "2023-01-19T03:39:40",
"upload_time_iso_8601": "2023-01-19T03:39:40.710864Z",
"url": "https://files.pythonhosted.org/packages/be/bf/a26b2934450b24485221f556aba7162a91b6963d56eb0d35fc77b90eda01/aws_cdk.aws_events_targets-1.189.0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2023-01-19 03:39:40",
"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-targets"
}