Skip to main content

Event targets for Amazon EventBridge

Project description

Event Targets for Amazon EventBridge

---

End-of-Support

AWS CDK v1 has reached End-of-Support on 2023-06-01. This package is no longer being updated, and users should migrate to AWS CDK v2.

For more information on how to migrate, see the Migrating to AWS CDK v2 guide.


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:

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. See the lambda example. Use escape hatches 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.

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.

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.

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

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 to the target.

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 to the target.

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.

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.

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.

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")))

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

aws-cdk.aws-events-targets-1.204.0.tar.gz (150.7 kB view details)

Uploaded Source

Built Distribution

File details

Details for the file aws-cdk.aws-events-targets-1.204.0.tar.gz.

File metadata

File hashes

Hashes for aws-cdk.aws-events-targets-1.204.0.tar.gz
Algorithm Hash digest
SHA256 a0bd96e2df1d2950182c26403b742f3373b55c75e445199e135a0c578db76cf4
MD5 b76f9c6b197d050a8b75defcaa6cb9ec
BLAKE2b-256 2a0fea72e2eb154f6702fb2a027d59fd28bf50947053b599aad202568d2a5d19

See more details on using hashes here.

File details

Details for the file aws_cdk.aws_events_targets-1.204.0-py3-none-any.whl.

File metadata

File hashes

Hashes for aws_cdk.aws_events_targets-1.204.0-py3-none-any.whl
Algorithm Hash digest
SHA256 100992d7fc0d9002f006ba27313d036e2038d3a8bf7cf2396fd8402b6005fb68
MD5 c19a284f3064bbca146021bb6cc1a4b6
BLAKE2b-256 96d03406b5850eb7e6dd8b5fdceaf62064f3eb9df6b5950940dadc69615d451c

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page