Skip to content
v2.277.0

Event Targets for Amazon EventBridge ​

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-lib/aws-events library for more information on EventBridge.

Event retry policy and using dead-letter queues ​

The Codebuild, CodePipeline, Lambda, Kinesis Data Streams, StepFunctions, LogGroup, SQSQueue, SNSTopic and ECSTask 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.

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

const fn = new lambda.Function(this, 'MyFunc', {
  runtime: lambda.Runtime.NODEJS_LATEST,
  handler: 'index.handler',
  code: lambda.Code.fromInline(`exports.handler = handler.toString()`),
});

const rule = new events.Rule(this, 'rule', {
  eventPattern: {
    source: ["aws.ec2"],
  },
});

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

rule.addTarget(new targets.LambdaFunction(fn, {
  deadLetterQueue: queue, // Optional: add a dead letter queue
  maxEventAge: Duration.hours(2), // Optional: set the maxEventAge retry policy
  retryAttempts: 2, // Optional: set the max number of retry attempts
}));
python
import aws_cdk.aws_lambda as lambda_


fn = lambda_.Function(self, "MyFunc",
    runtime=lambda_.Runtime.NODEJS_LATEST,
    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=Duration.hours(2),  # Optional: set the maxEventAge retry policy
    retry_attempts=2
))
java
import software.amazon.awscdk.services.lambda.*;


Function fn = Function.Builder.create(this, "MyFunc")
        .runtime(Runtime.NODEJS_LATEST)
        .handler("index.handler")
        .code(Code.fromInline("exports.handler = handler.toString()"))
        .build();

Rule rule = Rule.Builder.create(this, "rule")
        .eventPattern(EventPattern.builder()
                .source(List.of("aws.ec2"))
                .build())
        .build();

Queue queue = new Queue(this, "Queue");

rule.addTarget(LambdaFunction.Builder.create(fn)
        .deadLetterQueue(queue) // Optional: add a dead letter queue
        .maxEventAge(Duration.hours(2)) // Optional: set the maxEventAge retry policy
        .retryAttempts(2)
        .build());
csharp
using Amazon.CDK.AWS.Lambda;


var fn = new Function(this, "MyFunc", new FunctionProps {
    Runtime = Runtime.NODEJS_LATEST,
    Handler = "index.handler",
    Code = Code.FromInline("exports.handler = handler.toString()")
});

var rule = new Rule(this, "rule", new RuleProps {
    EventPattern = new EventPattern {
        Source = new [] { "aws.ec2" }
    }
});

var queue = new Queue(this, "Queue");

rule.AddTarget(new LambdaFunction(fn, new LambdaFunctionProps {
    DeadLetterQueue = queue,  // Optional: add a dead letter queue
    MaxEventAge = Duration.Hours(2),  // Optional: set the maxEventAge retry policy
    RetryAttempts = 2
}));
go
import "github.com/aws/aws-cdk-go/awscdk"


fn := lambda.NewFunction(this, jsii.String("MyFunc"), &FunctionProps{
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Handler: jsii.String("index.handler"),
	Code: lambda.Code_FromInline(jsii.String("exports.handler = handler.toString()")),
})

rule := events.NewRule(this, jsii.String("rule"), &RuleProps{
	EventPattern: &EventPattern{
		Source: []*string{
			jsii.String("aws.ec2"),
		},
	},
})

queue := sqs.NewQueue(this, jsii.String("Queue"))

rule.AddTarget(targets.NewLambdaFunction(fn, &LambdaFunctionProps{
	DeadLetterQueue: queue,
	 // Optional: add a dead letter queue
	MaxEventAge: awscdk.Duration_Hours(jsii.Number(2)),
	 // Optional: set the maxEventAge retry policy
	RetryAttempts: jsii.Number(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.

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

const logGroup = new logs.LogGroup(this, 'MyLogGroup', {
  logGroupName: 'MyLogGroup',
});

const rule = new events.Rule(this, 'rule', {
  eventPattern: {
    source: ["aws.ec2"],
  },
});

rule.addTarget(new targets.CloudWatchLogGroup(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))
java
import software.amazon.awscdk.services.logs.*;


LogGroup logGroup = LogGroup.Builder.create(this, "MyLogGroup")
        .logGroupName("MyLogGroup")
        .build();

Rule rule = Rule.Builder.create(this, "rule")
        .eventPattern(EventPattern.builder()
                .source(List.of("aws.ec2"))
                .build())
        .build();

rule.addTarget(new CloudWatchLogGroup(logGroup));
csharp
using Amazon.CDK.AWS.Logs;


var logGroup = new LogGroup(this, "MyLogGroup", new LogGroupProps {
    LogGroupName = "MyLogGroup"
});

var rule = new Rule(this, "rule", new RuleProps {
    EventPattern = new EventPattern {
        Source = new [] { "aws.ec2" }
    }
});

rule.AddTarget(new CloudWatchLogGroup(logGroup));
go
import logs "github.com/aws/aws-cdk-go/awscdk"


logGroup := logs.NewLogGroup(this, jsii.String("MyLogGroup"), &LogGroupProps{
	LogGroupName: jsii.String("MyLogGroup"),
})

rule := events.NewRule(this, jsii.String("rule"), &RuleProps{
	EventPattern: &EventPattern{
		Source: []*string{
			jsii.String("aws.ec2"),
		},
	},
})

rule.AddTarget(targets.NewCloudWatchLogGroup(logGroup))

A rule target input can also be specified to modify the event that is sent to the log group. Unlike other event targets, CloudWatchLogs requires a specific input template format.

ts
import * as logs from 'aws-cdk-lib/aws-logs';
declare const logGroup: logs.LogGroup;
declare const rule: events.Rule;

rule.addTarget(new targets.CloudWatchLogGroup(logGroup, {
  logEvent: targets.LogGroupTargetInput.fromObjectV2({
    timestamp: events.EventField.fromPath('$.time'),
    message: events.EventField.fromPath('$.detail-type'),
  }),
}));
python
import aws_cdk.aws_logs as logs
# log_group: logs.LogGroup
# rule: events.Rule


rule.add_target(targets.CloudWatchLogGroup(log_group,
    log_event=targets.LogGroupTargetInput.from_object_v2(
        timestamp=events.EventField.from_path("$.time"),
        message=events.EventField.from_path("$.detail-type")
    )
))
java
import software.amazon.awscdk.services.logs.*;
LogGroup logGroup;
Rule rule;


rule.addTarget(CloudWatchLogGroup.Builder.create(logGroup)
        .logEvent(LogGroupTargetInput.fromObjectV2(LogGroupTargetInputOptions.builder()
                .timestamp(EventField.fromPath("$.time"))
                .message(EventField.fromPath("$.detail-type"))
                .build()))
        .build());
csharp
using Amazon.CDK.AWS.Logs;
LogGroup logGroup;
Rule rule;


rule.AddTarget(new CloudWatchLogGroup(logGroup, new LogGroupProps {
    LogEvent = LogGroupTargetInput.FromObjectV2(new LogGroupTargetInputOptions {
        Timestamp = EventField.FromPath("$.time"),
        Message = EventField.FromPath("$.detail-type")
    })
}));
go
import logs "github.com/aws/aws-cdk-go/awscdk"
var logGroup LogGroup
var rule Rule


rule.AddTarget(targets.NewCloudWatchLogGroup(logGroup, &LogGroupProps{
	LogEvent: targets.LogGroupTargetInput_FromObjectV2(&LogGroupTargetInputOptions{
		Timestamp: events.EventField_FromPath(jsii.String("$.time")),
		Message: events.EventField_*FromPath(jsii.String("$.detail-type")),
	}),
}))

If you want to use static values to overwrite the message make sure that you provide a string value.

ts
import * as logs from 'aws-cdk-lib/aws-logs';
declare const logGroup: logs.LogGroup;
declare const rule: events.Rule;

rule.addTarget(new targets.CloudWatchLogGroup(logGroup, {
  logEvent: targets.LogGroupTargetInput.fromObjectV2({
    message: JSON.stringify({
      CustomField: 'CustomValue',
    }),
  }),
}));
python
import aws_cdk.aws_logs as logs
# log_group: logs.LogGroup
# rule: events.Rule


rule.add_target(targets.CloudWatchLogGroup(log_group,
    log_event=targets.LogGroupTargetInput.from_object_v2(
        message=JSON.stringify({
            "CustomField": "CustomValue"
        })
    )
))
java
import software.amazon.awscdk.services.logs.*;
LogGroup logGroup;
Rule rule;


rule.addTarget(CloudWatchLogGroup.Builder.create(logGroup)
        .logEvent(LogGroupTargetInput.fromObjectV2(LogGroupTargetInputOptions.builder()
                .message(JSON.stringify(Map.of(
                        "CustomField", "CustomValue")))
                .build()))
        .build());
csharp
using Amazon.CDK.AWS.Logs;
LogGroup logGroup;
Rule rule;


rule.AddTarget(new CloudWatchLogGroup(logGroup, new LogGroupProps {
    LogEvent = LogGroupTargetInput.FromObjectV2(new LogGroupTargetInputOptions {
        Message = JSON.Stringify(new Dictionary<string, string> {
            { "CustomField", "CustomValue" }
        })
    })
}));
go
import logs "github.com/aws/aws-cdk-go/awscdk"
var logGroup LogGroup
var rule Rule


rule.AddTarget(targets.NewCloudWatchLogGroup(logGroup, &LogGroupProps{
	LogEvent: targets.LogGroupTargetInput_FromObjectV2(&LogGroupTargetInputOptions{
		Message: jSON.stringify(map[string]*string{
			"CustomField": jsii.String("CustomValue"),
		}),
	}),
}))

The cloudwatch log event target will create an AWS custom resource internally which will default to set installLatestAwsSdk to true. This may be problematic for CN partition deployment. To workaround this issue, set installLatestAwsSdk to false.

ts
import * as logs from 'aws-cdk-lib/aws-logs';
declare const logGroup: logs.LogGroup;
declare const rule: events.Rule;

rule.addTarget(new targets.CloudWatchLogGroup(logGroup, {
  installLatestAwsSdk: false,
}));
python
import aws_cdk.aws_logs as logs
# log_group: logs.LogGroup
# rule: events.Rule


rule.add_target(targets.CloudWatchLogGroup(log_group,
    install_latest_aws_sdk=False
))
java
import software.amazon.awscdk.services.logs.*;
LogGroup logGroup;
Rule rule;


rule.addTarget(CloudWatchLogGroup.Builder.create(logGroup)
        .installLatestAwsSdk(false)
        .build());
csharp
using Amazon.CDK.AWS.Logs;
LogGroup logGroup;
Rule rule;


rule.AddTarget(new CloudWatchLogGroup(logGroup, new LogGroupProps {
    InstallLatestAwsSdk = false
}));
go
import logs "github.com/aws/aws-cdk-go/awscdk"
var logGroup LogGroup
var rule Rule


rule.AddTarget(targets.NewCloudWatchLogGroup(logGroup, &LogGroupProps{
	InstallLatestAwsSdk: jsii.Boolean(false),
}))

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.

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

const repo = new codecommit.Repository(this, 'MyRepo', {
  repositoryName: 'aws-cdk-codebuild-events',
});

const project = new codebuild.Project(this, 'MyProject', {
  source: codebuild.Source.codeCommit({ repository: repo }),
});

const deadLetterQueue = new sqs.Queue(this, 'DeadLetterQueue');

// trigger a build when a commit is pushed to the repo
const onCommitRule = repo.onCommit('OnCommit', {
  target: new targets.CodeBuildProject(project, {
    deadLetterQueue: deadLetterQueue,
  }),
  branches: ['master'],
});
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"]
)
java
import software.amazon.awscdk.services.codebuild.*;
import software.amazon.awscdk.services.codecommit.*;


Repository repo = Repository.Builder.create(this, "MyRepo")
        .repositoryName("aws-cdk-codebuild-events")
        .build();

Project project = Project.Builder.create(this, "MyProject")
        .source(Source.codeCommit(CodeCommitSourceProps.builder().repository(repo).build()))
        .build();

Queue deadLetterQueue = new Queue(this, "DeadLetterQueue");

// trigger a build when a commit is pushed to the repo
Rule onCommitRule = repo.onCommit("OnCommit", OnCommitOptions.builder()
        .target(CodeBuildProject.Builder.create(project)
                .deadLetterQueue(deadLetterQueue)
                .build())
        .branches(List.of("master"))
        .build());
csharp
using Amazon.CDK.AWS.CodeBuild;
using Amazon.CDK.AWS.CodeCommit;


var repo = new Repository(this, "MyRepo", new RepositoryProps {
    RepositoryName = "aws-cdk-codebuild-events"
});

var project = new Project(this, "MyProject", new ProjectProps {
    Source = Source.CodeCommit(new CodeCommitSourceProps { Repository = repo })
});

var deadLetterQueue = new Queue(this, "DeadLetterQueue");

// trigger a build when a commit is pushed to the repo
var onCommitRule = repo.OnCommit("OnCommit", new OnCommitOptions {
    Target = new CodeBuildProject(project, new CodeBuildProjectProps {
        DeadLetterQueue = deadLetterQueue
    }),
    Branches = new [] { "master" }
});
go
import "github.com/aws/aws-cdk-go/awscdk"
import codecommit "github.com/aws/aws-cdk-go/awscdk"


repo := codecommit.NewRepository(this, jsii.String("MyRepo"), &RepositoryProps{
	RepositoryName: jsii.String("aws-cdk-codebuild-events"),
})

project := codebuild.NewProject(this, jsii.String("MyProject"), &ProjectProps{
	Source: codebuild.Source_CodeCommit(&CodeCommitSourceProps{
		Repository: repo,
	}),
})

deadLetterQueue := sqs.NewQueue(this, jsii.String("DeadLetterQueue"))

// trigger a build when a commit is pushed to the repo
onCommitRule := repo.onCommit(jsii.String("OnCommit"), &OnCommitOptions{
	Target: targets.NewCodeBuildProject(project, &CodeBuildProjectProps{
		DeadLetterQueue: deadLetterQueue,
	}),
	Branches: []*string{
		jsii.String("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

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

const pipeline = new codepipeline.Pipeline(this, 'Pipeline');

const rule = new events.Rule(this, 'Rule', {
  schedule: events.Schedule.expression('rate(1 hour)'),
});

rule.addTarget(new targets.CodePipeline(pipeline));
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))
java
import software.amazon.awscdk.services.codepipeline.*;


Pipeline pipeline = new Pipeline(this, "Pipeline");

Rule rule = Rule.Builder.create(this, "Rule")
        .schedule(Schedule.expression("rate(1 hour)"))
        .build();

rule.addTarget(new CodePipeline(pipeline));
csharp
using Amazon.CDK.AWS.CodePipeline;


var pipeline = new Pipeline(this, "Pipeline");

var rule = new Rule(this, "Rule", new RuleProps {
    Schedule = Schedule.Expression("rate(1 hour)")
});

rule.AddTarget(new CodePipeline(pipeline));
go
import codepipeline "github.com/aws/aws-cdk-go/awscdk"


pipeline := codepipeline.NewPipeline(this, jsii.String("Pipeline"))

rule := events.NewRule(this, jsii.String("Rule"), &RuleProps{
	Schedule: events.Schedule_Expression(jsii.String("rate(1 hour)")),
})

rule.AddTarget(targets.NewCodePipeline(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.

ts
import * as iam from 'aws-cdk-lib/aws-iam';
import * as sfn from 'aws-cdk-lib/aws-stepfunctions';

const rule = new events.Rule(this, 'Rule', {
  schedule: events.Schedule.rate(Duration.minutes(1)),
});

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

const role = new iam.Role(this, 'Role', {
  assumedBy: new iam.ServicePrincipal('events.amazonaws.com'),
});
const stateMachine = new sfn.StateMachine(this, 'SM', {
  definition: new sfn.Wait(this, 'Hello', { time: sfn.WaitTime.duration(Duration.seconds(10)) })
});

rule.addTarget(new targets.SfnStateMachine(stateMachine, {
  input: events.RuleTargetInput.fromObject({ SomeParam: 'SomeValue' }),
  deadLetterQueue: dlq,
  role: role
}));
python
import aws_cdk.aws_iam as iam
import aws_cdk.aws_stepfunctions as sfn


rule = events.Rule(self, "Rule",
    schedule=events.Schedule.rate(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(Duration.seconds(10)))
)

rule.add_target(targets.SfnStateMachine(state_machine,
    input=events.RuleTargetInput.from_object({"SomeParam": "SomeValue"}),
    dead_letter_queue=dlq,
    role=role
))
java
import software.amazon.awscdk.services.iam.*;
import software.amazon.awscdk.services.stepfunctions.*;


Rule rule = Rule.Builder.create(this, "Rule")
        .schedule(Schedule.rate(Duration.minutes(1)))
        .build();

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

Role role = Role.Builder.create(this, "Role")
        .assumedBy(new ServicePrincipal("events.amazonaws.com"))
        .build();
StateMachine stateMachine = StateMachine.Builder.create(this, "SM")
        .definition(Wait.Builder.create(this, "Hello").time(WaitTime.duration(Duration.seconds(10))).build())
        .build();

rule.addTarget(SfnStateMachine.Builder.create(stateMachine)
        .input(RuleTargetInput.fromObject(Map.of("SomeParam", "SomeValue")))
        .deadLetterQueue(dlq)
        .role(role)
        .build());
csharp
using Amazon.CDK.AWS.IAM;
using Amazon.CDK.AWS.StepFunctions;


var rule = new Rule(this, "Rule", new RuleProps {
    Schedule = Schedule.Rate(Duration.Minutes(1))
});

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

var role = new Role(this, "Role", new RoleProps {
    AssumedBy = new ServicePrincipal("events.amazonaws.com")
});
var stateMachine = new StateMachine(this, "SM", new StateMachineProps {
    Definition = new Wait(this, "Hello", new WaitProps { Time = WaitTime.Duration(Duration.Seconds(10)) })
});

rule.AddTarget(new SfnStateMachine(stateMachine, new SfnStateMachineProps {
    Input = RuleTargetInput.FromObject(new Dictionary<string, string> { { "SomeParam", "SomeValue" } }),
    DeadLetterQueue = dlq,
    Role = role
}));
go
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"


rule := events.NewRule(this, jsii.String("Rule"), &RuleProps{
	Schedule: events.Schedule_Rate(awscdk.Duration_Minutes(jsii.Number(1))),
})

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

role := iam.NewRole(this, jsii.String("Role"), &RoleProps{
	AssumedBy: iam.NewServicePrincipal(jsii.String("events.amazonaws.com")),
})
stateMachine := sfn.NewStateMachine(this, jsii.String("SM"), &StateMachineProps{
	Definition: sfn.NewWait(this, jsii.String("Hello"), &WaitProps{
		Time: sfn.WaitTime_Duration(awscdk.Duration_Seconds(jsii.Number(10))),
	}),
})

rule.AddTarget(targets.NewSfnStateMachine(stateMachine, &SfnStateMachineProps{
	Input: events.RuleTargetInput_FromObject(map[string]*string{
		"SomeParam": jsii.String("SomeValue"),
	}),
	DeadLetterQueue: 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.

ts
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as ecs from 'aws-cdk-lib/aws-ecs';
import * as batch from 'aws-cdk-lib/aws-batch';
import { ContainerImage } from 'aws-cdk-lib/aws-ecs';

declare const vpc: ec2.Vpc;

const computeEnvironment = new batch.FargateComputeEnvironment(this, 'ComputeEnv', {
  vpc,
});

const jobQueue = new batch.JobQueue(this, 'JobQueue', {
  priority: 1,
  computeEnvironments: [
    {
      computeEnvironment,
      order: 1,
    },
  ],
});

const jobDefinition = new batch.EcsJobDefinition(this, 'MyJob', {
  container: new batch.EcsEc2ContainerDefinition(this, 'Container', {
    image: ecs.ContainerImage.fromRegistry('test-repo'),
    memory: cdk.Size.mebibytes(2048),
    cpu: 256,
  }),
});

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

const rule = new events.Rule(this, 'Rule', {
  schedule: events.Schedule.rate(Duration.hours(1)),
});

rule.addTarget(new targets.BatchJob(
  jobQueue.jobQueueArn,
  jobQueue,
  jobDefinition.jobDefinitionArn,
  jobDefinition,
  {
    deadLetterQueue: queue,
    event: events.RuleTargetInput.fromObject({ SomeParam: 'SomeValue' }),
    retryAttempts: 2,
    maxEventAge: Duration.hours(2),
  },
));
python
import aws_cdk.aws_ec2 as ec2
import aws_cdk.aws_ecs as ecs
import aws_cdk.aws_batch as batch
from aws_cdk.aws_ecs import ContainerImage

# vpc: ec2.Vpc


compute_environment = batch.FargateComputeEnvironment(self, "ComputeEnv",
    vpc=vpc
)

job_queue = batch.JobQueue(self, "JobQueue",
    priority=1,
    compute_environments=[batch.OrderedComputeEnvironment(
        compute_environment=compute_environment,
        order=1
    )
    ]
)

job_definition = batch.EcsJobDefinition(self, "MyJob",
    container=batch.EcsEc2ContainerDefinition(self, "Container",
        image=ecs.ContainerImage.from_registry("test-repo"),
        memory=cdk.Size.mebibytes(2048),
        cpu=256
    )
)

queue = sqs.Queue(self, "Queue")

rule = events.Rule(self, "Rule",
    schedule=events.Schedule.rate(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=Duration.hours(2)
))
java
import software.amazon.awscdk.services.ec2.*;
import software.amazon.awscdk.services.ecs.*;
import software.amazon.awscdk.services.batch.*;
import software.amazon.awscdk.services.ecs.ContainerImage;

Vpc vpc;


FargateComputeEnvironment computeEnvironment = FargateComputeEnvironment.Builder.create(this, "ComputeEnv")
        .vpc(vpc)
        .build();

JobQueue jobQueue = JobQueue.Builder.create(this, "JobQueue")
        .priority(1)
        .computeEnvironments(List.of(OrderedComputeEnvironment.builder()
                .computeEnvironment(computeEnvironment)
                .order(1)
                .build()))
        .build();

EcsJobDefinition jobDefinition = EcsJobDefinition.Builder.create(this, "MyJob")
        .container(EcsEc2ContainerDefinition.Builder.create(this, "Container")
                .image(ContainerImage.fromRegistry("test-repo"))
                .memory(Size.mebibytes(2048))
                .cpu(256)
                .build())
        .build();

Queue queue = new Queue(this, "Queue");

Rule rule = Rule.Builder.create(this, "Rule")
        .schedule(Schedule.rate(Duration.hours(1)))
        .build();

rule.addTarget(BatchJob.Builder.create(jobQueue.getJobQueueArn(), jobQueue, jobDefinition.getJobDefinitionArn(), jobDefinition)
        .deadLetterQueue(queue)
        .event(RuleTargetInput.fromObject(Map.of("SomeParam", "SomeValue")))
        .retryAttempts(2)
        .maxEventAge(Duration.hours(2))
        .build());
csharp
using Amazon.CDK.AWS.EC2;
using Amazon.CDK.AWS.ECS;
using Amazon.CDK.AWS.Batch;

Vpc vpc;


var computeEnvironment = new FargateComputeEnvironment(this, "ComputeEnv", new FargateComputeEnvironmentProps {
    Vpc = vpc
});

var jobQueue = new JobQueue(this, "JobQueue", new JobQueueProps {
    Priority = 1,
    ComputeEnvironments = new [] { new OrderedComputeEnvironment {
        ComputeEnvironment = computeEnvironment,
        Order = 1
    } }
});

var jobDefinition = new EcsJobDefinition(this, "MyJob", new EcsJobDefinitionProps {
    Container = new EcsEc2ContainerDefinition(this, "Container", new EcsEc2ContainerDefinitionProps {
        Image = ContainerImage.FromRegistry("test-repo"),
        Memory = Size.Mebibytes(2048),
        Cpu = 256
    })
});

var queue = new Queue(this, "Queue");

var rule = new Rule(this, "Rule", new RuleProps {
    Schedule = Schedule.Rate(Duration.Hours(1))
});

rule.AddTarget(new BatchJob(jobQueue.JobQueueArn, jobQueue, jobDefinition.JobDefinitionArn, jobDefinition, new BatchJobProps {
    DeadLetterQueue = queue,
    Event = RuleTargetInput.FromObject(new Dictionary<string, string> { { "SomeParam", "SomeValue" } }),
    RetryAttempts = 2,
    MaxEventAge = Duration.Hours(2)
}));
go
import ec2 "github.com/aws/aws-cdk-go/awscdk"
import ecs "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"

var vpc Vpc


computeEnvironment := batch.NewFargateComputeEnvironment(this, jsii.String("ComputeEnv"), &FargateComputeEnvironmentProps{
	Vpc: Vpc,
})

jobQueue := batch.NewJobQueue(this, jsii.String("JobQueue"), &JobQueueProps{
	Priority: jsii.Number(1),
	ComputeEnvironments: []OrderedComputeEnvironment{
		&OrderedComputeEnvironment{
			ComputeEnvironment: *ComputeEnvironment,
			Order: jsii.Number(1),
		},
	},
})

jobDefinition := batch.NewEcsJobDefinition(this, jsii.String("MyJob"), &EcsJobDefinitionProps{
	Container: batch.NewEcsEc2ContainerDefinition(this, jsii.String("Container"), &EcsEc2ContainerDefinitionProps{
		Image: ecs.ContainerImage_FromRegistry(jsii.String("test-repo")),
		Memory: cdk.Size_Mebibytes(jsii.Number(2048)),
		Cpu: jsii.Number(256),
	}),
})

queue := sqs.NewQueue(this, jsii.String("Queue"))

rule := events.NewRule(this, jsii.String("Rule"), &RuleProps{
	Schedule: events.Schedule_Rate(awscdk.Duration_Hours(jsii.Number(1))),
})

rule.AddTarget(targets.NewBatchJob(jobQueue.jobQueueArn, jobQueue, jobDefinition.jobDefinitionArn, jobDefinition, &BatchJobProps{
	DeadLetterQueue: queue,
	Event: events.RuleTargetInput_FromObject(map[string]*string{
		"SomeParam": jsii.String("SomeValue"),
	}),
	RetryAttempts: jsii.Number(2),
	MaxEventAge: awscdk.Duration_*Hours(jsii.Number(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.

ts
import * as api from 'aws-cdk-lib/aws-apigateway';
import * as lambda from 'aws-cdk-lib/aws-lambda';

const rule = new events.Rule(this, 'Rule', {
  schedule: events.Schedule.rate(Duration.minutes(1)),
});

const fn = new lambda.Function( this, 'MyFunc', {
  handler: 'index.handler',
  runtime: lambda.Runtime.NODEJS_LATEST,
  code: lambda.Code.fromInline( 'exports.handler = e => {}' ),
} );

const restApi = new api.LambdaRestApi( this, 'MyRestAPI', { handler: fn } );

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

rule.addTarget(
  new targets.ApiGateway( restApi, {
    path: '/*/test',
    method: 'GET',
    stage:  'prod',
    pathParameterValues: ['path-value'],
    headerParameters: {
      Header1: 'header1',
    },
    queryStringParameters: {
      QueryParam1: 'query-param-1',
    },
    deadLetterQueue: dlq
  } ),
)
python
import aws_cdk.aws_apigateway as api
import aws_cdk.aws_lambda as lambda_


rule = events.Rule(self, "Rule",
    schedule=events.Schedule.rate(Duration.minutes(1))
)

fn = lambda_.Function(self, "MyFunc",
    handler="index.handler",
    runtime=lambda_.Runtime.NODEJS_LATEST,
    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
    ))
java
import software.amazon.awscdk.services.apigateway.*;
import software.amazon.awscdk.services.lambda.*;


Rule rule = Rule.Builder.create(this, "Rule")
        .schedule(Schedule.rate(Duration.minutes(1)))
        .build();

Function fn = Function.Builder.create(this, "MyFunc")
        .handler("index.handler")
        .runtime(Runtime.NODEJS_LATEST)
        .code(Code.fromInline("exports.handler = e => {}"))
        .build();

LambdaRestApi restApi = LambdaRestApi.Builder.create(this, "MyRestAPI").handler(fn).build();

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

rule.addTarget(
ApiGateway.Builder.create(restApi)
        .path("/*/test")
        .method("GET")
        .stage("prod")
        .pathParameterValues(List.of("path-value"))
        .headerParameters(Map.of(
                "Header1", "header1"))
        .queryStringParameters(Map.of(
                "QueryParam1", "query-param-1"))
        .deadLetterQueue(dlq)
        .build());
csharp
using Amazon.CDK.AWS.APIGateway;
using Amazon.CDK.AWS.Lambda;


var rule = new Rule(this, "Rule", new RuleProps {
    Schedule = Schedule.Rate(Duration.Minutes(1))
});

var fn = new Function(this, "MyFunc", new FunctionProps {
    Handler = "index.handler",
    Runtime = Runtime.NODEJS_LATEST,
    Code = Code.FromInline("exports.handler = e => {}")
});

var restApi = new LambdaRestApi(this, "MyRestAPI", new LambdaRestApiProps { Handler = fn });

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

rule.AddTarget(
new ApiGateway(restApi, new ApiGatewayProps {
    Path = "/*/test",
    Method = "GET",
    Stage = "prod",
    PathParameterValues = new [] { "path-value" },
    HeaderParameters = new Dictionary<string, string> {
        { "Header1", "header1" }
    },
    QueryStringParameters = new Dictionary<string, string> {
        { "QueryParam1", "query-param-1" }
    },
    DeadLetterQueue = dlq
}));
go
import api "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"


rule := events.NewRule(this, jsii.String("Rule"), &RuleProps{
	Schedule: events.Schedule_Rate(awscdk.Duration_Minutes(jsii.Number(1))),
})

fn := lambda.NewFunction(this, jsii.String("MyFunc"), &FunctionProps{
	Handler: jsii.String("index.handler"),
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Code: lambda.Code_FromInline(jsii.String("exports.handler = e => {}")),
})

restApi := api.NewLambdaRestApi(this, jsii.String("MyRestAPI"), &LambdaRestApiProps{
	Handler: fn,
})

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

rule.AddTarget(
targets.NewApiGateway(restApi, &ApiGatewayProps{
	Path: jsii.String("/*/test"),
	Method: jsii.String("GET"),
	Stage: jsii.String("prod"),
	PathParameterValues: []*string{
		jsii.String("path-value"),
	},
	HeaderParameters: map[string]*string{
		"Header1": jsii.String("header1"),
	},
	QueryStringParameters: map[string]*string{
		"QueryParam1": jsii.String("query-param-1"),
	},
	DeadLetterQueue: dlq,
}))

Invoke an API Gateway V2 HTTP API ​

Use the ApiGatewayV2 target to trigger a HTTP API.

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

declare const httpApi: apigwv2.HttpApi;
declare const rule: events.Rule;

rule.addTarget(new targets.ApiGatewayV2(httpApi));
python
import aws_cdk.aws_apigatewayv2 as apigwv2

# http_api: apigwv2.HttpApi
# rule: events.Rule


rule.add_target(targets.ApiGatewayV2(http_api))
java
import software.amazon.awscdk.services.apigatewayv2.*;

HttpApi httpApi;
Rule rule;


rule.addTarget(new ApiGatewayV2(httpApi));
csharp
using Amazon.CDK.AWS.Apigatewayv2;

HttpApi httpApi;
Rule rule;


rule.AddTarget(new ApiGatewayV2(httpApi));
go
import apigwv2 "github.com/aws/aws-cdk-go/awscdk"

var httpApi HttpApi
var rule Rule


rule.AddTarget(targets.NewApiGatewayV2(httpApi))

Invoke an AWS API ​

Use the AwsApi target to make direct AWS API calls from EventBridge rules. This is useful for invoking AWS services that don't have a dedicated EventBridge target.

Basic Usage ​

The following example shows how to update an ECS service when a rule is triggered:

ts
const rule = new events.Rule(this, 'Rule', {
  schedule: events.Schedule.rate(Duration.hours(1)),
});

rule.addTarget(new targets.AwsApi({
  service: 'ECS',
  action: 'updateService',
  parameters: {
    service: 'my-service',
    forceNewDeployment: true,
  },
}));
python
rule = events.Rule(self, "Rule",
    schedule=events.Schedule.rate(Duration.hours(1))
)

rule.add_target(targets.AwsApi(
    service="ECS",
    action="updateService",
    parameters={
        "service": "my-service",
        "force_new_deployment": True
    }
))
java
Rule rule = Rule.Builder.create(this, "Rule")
        .schedule(Schedule.rate(Duration.hours(1)))
        .build();

rule.addTarget(AwsApi.Builder.create()
        .service("ECS")
        .action("updateService")
        .parameters(Map.of(
                "service", "my-service",
                "forceNewDeployment", true))
        .build());
csharp
var rule = new Rule(this, "Rule", new RuleProps {
    Schedule = Schedule.Rate(Duration.Hours(1))
});

rule.AddTarget(new AwsApi(new AwsApiProps {
    Service = "ECS",
    Action = "updateService",
    Parameters = new Dictionary<string, object> {
        { "service", "my-service" },
        { "forceNewDeployment", true }
    }
}));
go
rule := events.NewRule(this, jsii.String("Rule"), &RuleProps{
	Schedule: events.Schedule_Rate(awscdk.Duration_Hours(jsii.Number(1))),
})

rule.AddTarget(targets.NewAwsApi(&AwsApiProps{
	Service: jsii.String("ECS"),
	Action: jsii.String("updateService"),
	Parameters: map[string]interface{}{
		"service": jsii.String("my-service"),
		"forceNewDeployment": jsii.Boolean(true),
	},
}))

IAM Permissions ​

By default, the AwsApi target automatically creates the necessary IAM permissions based on the service and action you specify. The permission format follows the pattern: service:Action.

For example:

  • ECS service with updateService action → ecs:UpdateService permission
  • RDS service with createDBSnapshot action → rds:CreateDBSnapshot permission

Custom IAM Policy ​

In some cases, you may need to provide a custom IAM policy statement, especially when:

  • You need to restrict permissions to specific resources (instead of *)
  • The service requires additional permissions beyond the main action
  • You want more granular control over the permissions
ts
import * as iam from 'aws-cdk-lib/aws-iam';
import * as s3 from 'aws-cdk-lib/aws-s3';

declare const rule: events.Rule;
declare const bucket: s3.Bucket;

rule.addTarget(new targets.AwsApi({
  service: 's3',
  action: 'GetBucketEncryption',
  parameters: {
    Bucket: bucket.bucketName,
  },
  policyStatement: new iam.PolicyStatement({
    effect: iam.Effect.ALLOW,
    actions: ['s3:GetEncryptionConfiguration'],
    resources: [bucket.bucketArn],
  }),
}));
python
import aws_cdk.aws_iam as iam
import aws_cdk.aws_s3 as s3

# rule: events.Rule
# bucket: s3.Bucket


rule.add_target(targets.AwsApi(
    service="s3",
    action="GetBucketEncryption",
    parameters={
        "Bucket": bucket.bucket_name
    },
    policy_statement=iam.PolicyStatement(
        effect=iam.Effect.ALLOW,
        actions=["s3:GetEncryptionConfiguration"],
        resources=[bucket.bucket_arn]
    )
))
java
import software.amazon.awscdk.services.iam.*;
import software.amazon.awscdk.services.s3.*;

Rule rule;
Bucket bucket;


rule.addTarget(AwsApi.Builder.create()
        .service("s3")
        .action("GetBucketEncryption")
        .parameters(Map.of(
                "Bucket", bucket.getBucketName()))
        .policyStatement(PolicyStatement.Builder.create()
                .effect(Effect.ALLOW)
                .actions(List.of("s3:GetEncryptionConfiguration"))
                .resources(List.of(bucket.getBucketArn()))
                .build())
        .build());
csharp
using Amazon.CDK.AWS.IAM;
using Amazon.CDK.AWS.S3;

Rule rule;
Bucket bucket;


rule.AddTarget(new AwsApi(new AwsApiProps {
    Service = "s3",
    Action = "GetBucketEncryption",
    Parameters = new Dictionary<string, string> {
        { "Bucket", bucket.BucketName }
    },
    PolicyStatement = new PolicyStatement(new PolicyStatementProps {
        Effect = Effect.ALLOW,
        Actions = new [] { "s3:GetEncryptionConfiguration" },
        Resources = new [] { bucket.BucketArn }
    })
}));
go
import "github.com/aws/aws-cdk-go/awscdk"
import s3 "github.com/aws/aws-cdk-go/awscdk"

var rule Rule
var bucket Bucket


rule.AddTarget(targets.NewAwsApi(&AwsApiProps{
	Service: jsii.String("s3"),
	Action: jsii.String("GetBucketEncryption"),
	Parameters: map[string]*string{
		"Bucket": bucket.bucketName,
	},
	PolicyStatement: iam.NewPolicyStatement(&PolicyStatementProps{
		Effect: iam.Effect_ALLOW,
		Actions: []*string{
			jsii.String("s3:GetEncryptionConfiguration"),
		},
		Resources: []*string{
			bucket.bucketArn,
		},
	}),
}))

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.

ts
const connection = new events.Connection(this, 'Connection', {
  authorization: events.Authorization.apiKey('x-api-key', SecretValue.secretsManager('ApiSecretName')),
  description: 'Connection with API Key x-api-key',
});

const destination = new events.ApiDestination(this, 'Destination', {
  connection,
  endpoint: 'https://example.com',
  description: 'Calling example.com with API key x-api-key',
});

const rule = new events.Rule(this, 'Rule', {
  schedule: events.Schedule.rate(Duration.minutes(1)),
  targets: [new targets.ApiDestination(destination)],
});
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(Duration.minutes(1)),
    targets=[targets.ApiDestination(destination)]
)
java
Connection connection = Connection.Builder.create(this, "Connection")
        .authorization(Authorization.apiKey("x-api-key", SecretValue.secretsManager("ApiSecretName")))
        .description("Connection with API Key x-api-key")
        .build();

ApiDestination destination = ApiDestination.Builder.create(this, "Destination")
        .connection(connection)
        .endpoint("https://example.com")
        .description("Calling example.com with API key x-api-key")
        .build();

Rule rule = Rule.Builder.create(this, "Rule")
        .schedule(Schedule.rate(Duration.minutes(1)))
        .targets(List.of(new ApiDestination(destination)))
        .build();
csharp
var connection = new Connection(this, "Connection", new ConnectionProps {
    Authorization = Authorization.ApiKey("x-api-key", SecretValue.SecretsManager("ApiSecretName")),
    Description = "Connection with API Key x-api-key"
});

var destination = new ApiDestination(this, "Destination", new ApiDestinationProps {
    Connection = connection,
    Endpoint = "https://example.com",
    Description = "Calling example.com with API key x-api-key"
});

var rule = new Rule(this, "Rule", new RuleProps {
    Schedule = Schedule.Rate(Duration.Minutes(1)),
    Targets = new [] { new ApiDestination(destination) }
});
go
connection := events.NewConnection(this, jsii.String("Connection"), &ConnectionProps{
	Authorization: events.Authorization_ApiKey(jsii.String("x-api-key"), awscdk.SecretValue_SecretsManager(jsii.String("ApiSecretName"))),
	Description: jsii.String("Connection with API Key x-api-key"),
})

destination := events.NewApiDestination(this, jsii.String("Destination"), &ApiDestinationProps{
	Connection: Connection,
	Endpoint: jsii.String("https://example.com"),
	Description: jsii.String("Calling example.com with API key x-api-key"),
})

rule := events.NewRule(this, jsii.String("Rule"), &RuleProps{
	Schedule: events.Schedule_Rate(awscdk.Duration_Minutes(jsii.Number(1))),
	Targets: []IRuleTarget{
		targets.NewApiDestination(destination),
	},
})

You can also import an existing connection and destination to create additional rules:

ts
const connection = events.Connection.fromEventBusArn(
  this,
  'Connection',
  'arn:aws:events:us-east-1:123456789012:event-bus/EventBusName',
  'arn:aws:secretsmanager:us-east-1:123456789012:secret:SecretName-f3gDy9',
);

const apiDestinationArn = 'arn:aws:events:us-east-1:123456789012:api-destination/DestinationName/11111111-1111-1111-1111-111111111111';
const apiDestinationArnForPolicy = 'arn:aws:events:us-east-1:123456789012:api-destination/DestinationName';
const destination = events.ApiDestination.fromApiDestinationAttributes(
  this,
  'Destination',
  {
    apiDestinationArn,
    connection,
    apiDestinationArnForPolicy // optional
  },
);

const rule = new events.Rule(this, 'OtherRule', {
  schedule: events.Schedule.rate(Duration.minutes(10)),
  targets: [new targets.ApiDestination(destination)],
});
python
connection = events.Connection.from_event_bus_arn(self, "Connection", "arn:aws:events:us-east-1:123456789012:event-bus/EventBusName", "arn:aws:secretsmanager:us-east-1:123456789012:secret:SecretName-f3gDy9")

api_destination_arn = "arn:aws:events:us-east-1:123456789012:api-destination/DestinationName/11111111-1111-1111-1111-111111111111"
api_destination_arn_for_policy = "arn:aws:events:us-east-1:123456789012:api-destination/DestinationName"
destination = events.ApiDestination.from_api_destination_attributes(self, "Destination",
    api_destination_arn=api_destination_arn,
    connection=connection,
    api_destination_arn_for_policy=api_destination_arn_for_policy
)

rule = events.Rule(self, "OtherRule",
    schedule=events.Schedule.rate(Duration.minutes(10)),
    targets=[targets.ApiDestination(destination)]
)
java
IConnection connection = Connection.fromEventBusArn(this, "Connection", "arn:aws:events:us-east-1:123456789012:event-bus/EventBusName", "arn:aws:secretsmanager:us-east-1:123456789012:secret:SecretName-f3gDy9");

String apiDestinationArn = "arn:aws:events:us-east-1:123456789012:api-destination/DestinationName/11111111-1111-1111-1111-111111111111";
String apiDestinationArnForPolicy = "arn:aws:events:us-east-1:123456789012:api-destination/DestinationName";
IApiDestination destination = ApiDestination.fromApiDestinationAttributes(this, "Destination", ApiDestinationAttributes.builder()
        .apiDestinationArn(apiDestinationArn)
        .connection(connection)
        .apiDestinationArnForPolicy(apiDestinationArnForPolicy)
        .build());

Rule rule = Rule.Builder.create(this, "OtherRule")
        .schedule(Schedule.rate(Duration.minutes(10)))
        .targets(List.of(new ApiDestination(destination)))
        .build();
csharp
var connection = Connection.FromEventBusArn(this, "Connection", "arn:aws:events:us-east-1:123456789012:event-bus/EventBusName", "arn:aws:secretsmanager:us-east-1:123456789012:secret:SecretName-f3gDy9");

var apiDestinationArn = "arn:aws:events:us-east-1:123456789012:api-destination/DestinationName/11111111-1111-1111-1111-111111111111";
var apiDestinationArnForPolicy = "arn:aws:events:us-east-1:123456789012:api-destination/DestinationName";
var destination = ApiDestination.FromApiDestinationAttributes(this, "Destination", new ApiDestinationAttributes {
    ApiDestinationArn = apiDestinationArn,
    Connection = connection,
    ApiDestinationArnForPolicy = apiDestinationArnForPolicy
});

var rule = new Rule(this, "OtherRule", new RuleProps {
    Schedule = Schedule.Rate(Duration.Minutes(10)),
    Targets = new [] { new ApiDestination(destination) }
});
go
connection := events.Connection_FromEventBusArn(this, jsii.String("Connection"), jsii.String("arn:aws:events:us-east-1:123456789012:event-bus/EventBusName"), jsii.String("arn:aws:secretsmanager:us-east-1:123456789012:secret:SecretName-f3gDy9"))

apiDestinationArn := "arn:aws:events:us-east-1:123456789012:api-destination/DestinationName/11111111-1111-1111-1111-111111111111"
apiDestinationArnForPolicy := "arn:aws:events:us-east-1:123456789012:api-destination/DestinationName"
destination := events.ApiDestination_FromApiDestinationAttributes(this, jsii.String("Destination"), &ApiDestinationAttributes{
	ApiDestinationArn: jsii.String(ApiDestinationArn),
	Connection: Connection,
	ApiDestinationArnForPolicy: jsii.String(ApiDestinationArnForPolicy),
})

rule := events.NewRule(this, jsii.String("OtherRule"), &RuleProps{
	Schedule: events.Schedule_Rate(awscdk.Duration_Minutes(jsii.Number(10))),
	Targets: []IRuleTarget{
		targets.NewApiDestination(destination),
	},
})

Invoke an AppSync GraphQL API ​

Use the AppSync target to trigger an AppSync GraphQL API. You need to create an AppSync.GraphqlApi configured with AWS_IAM authorization mode.

The code snippet below creates an AppSync GraphQL API target that is invoked every hour, calling the publish mutation.

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

const api = new appsync.GraphqlApi(this, 'api', {
  name: 'api',
  definition: appsync.Definition.fromFile('schema.graphql'),
  authorizationConfig: {
    defaultAuthorization: { authorizationType: appsync.AuthorizationType.IAM }
  },
});

const rule = new events.Rule(this, 'Rule', {
  schedule: events.Schedule.rate(cdk.Duration.hours(1)),
});

rule.addTarget(new targets.AppSync(api, {
  graphQLOperation: 'mutation Publish($message: String!){ publish(message: $message) { message } }',
  variables: events.RuleTargetInput.fromObject({
    message: 'hello world',
  }),
}));
python
import aws_cdk.aws_appsync as appsync


api = appsync.GraphqlApi(self, "api",
    name="api",
    definition=appsync.Definition.from_file("schema.graphql"),
    authorization_config=appsync.AuthorizationConfig(
        default_authorization=appsync.AuthorizationMode(authorization_type=appsync.AuthorizationType.IAM)
    )
)

rule = events.Rule(self, "Rule",
    schedule=events.Schedule.rate(cdk.Duration.hours(1))
)

rule.add_target(targets.AppSync(api,
    graph_ql_operation="mutation Publish($message: String!){ publish(message: $message) { message } }",
    variables=events.RuleTargetInput.from_object({
        "message": "hello world"
    })
))
java
import software.amazon.awscdk.services.appsync.*;


GraphqlApi api = GraphqlApi.Builder.create(this, "api")
        .name("api")
        .definition(Definition.fromFile("schema.graphql"))
        .authorizationConfig(AuthorizationConfig.builder()
                .defaultAuthorization(AuthorizationMode.builder().authorizationType(AuthorizationType.IAM).build())
                .build())
        .build();

Rule rule = Rule.Builder.create(this, "Rule")
        .schedule(Schedule.rate(Duration.hours(1)))
        .build();

rule.addTarget(AppSync.Builder.create(api)
        .graphQLOperation("mutation Publish($message: String!){ publish(message: $message) { message } }")
        .variables(RuleTargetInput.fromObject(Map.of(
                "message", "hello world")))
        .build());
csharp
using Amazon.CDK.AWS.AppSync;


var api = new GraphqlApi(this, "api", new GraphqlApiProps {
    Name = "api",
    Definition = Definition.FromFile("schema.graphql"),
    AuthorizationConfig = new AuthorizationConfig {
        DefaultAuthorization = new AuthorizationMode { AuthorizationType = AuthorizationType.IAM }
    }
});

var rule = new Rule(this, "Rule", new RuleProps {
    Schedule = Schedule.Rate(Duration.Hours(1))
});

rule.AddTarget(new AppSync(api, new AppSyncGraphQLApiProps {
    GraphQLOperation = "mutation Publish($message: String!){ publish(message: $message) { message } }",
    Variables = RuleTargetInput.FromObject(new Dictionary<string, string> {
        { "message", "hello world" }
    })
}));
go
import "github.com/aws/aws-cdk-go/awscdk"


api := appsync.NewGraphqlApi(this, jsii.String("api"), &GraphqlApiProps{
	Name: jsii.String("api"),
	Definition: appsync.Definition_FromFile(jsii.String("schema.graphql")),
	AuthorizationConfig: &AuthorizationConfig{
		DefaultAuthorization: &AuthorizationMode{
			AuthorizationType: appsync.AuthorizationType_IAM,
		},
	},
})

rule := events.NewRule(this, jsii.String("Rule"), &RuleProps{
	Schedule: events.Schedule_Rate(cdk.Duration_Hours(jsii.Number(1))),
})

rule.AddTarget(targets.NewAppSync(api, &AppSyncGraphQLApiProps{
	GraphQLOperation: jsii.String("mutation Publish($message: String!){ publish(message: $message) { message } }"),
	Variables: events.RuleTargetInput_FromObject(map[string]*string{
		"message": jsii.String("hello world"),
	}),
}))

You can pass an existing role with the proper permissions to be used for the target when the rule is triggered. The code snippet below uses an existing role and grants permissions to use the publish Mutation on the GraphQL API.

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

const api = appsync.GraphqlApi.fromGraphqlApiAttributes(this, 'ImportedAPI', {
  graphqlApiId: '<api-id>',
  graphqlApiArn: '<api-arn>',
  graphQLEndpointArn: '<api-endpoint-arn>',
  visibility: appsync.Visibility.GLOBAL,
  modes: [appsync.AuthorizationType.IAM],
});

const rule = new events.Rule(this, 'Rule', { schedule: events.Schedule.rate(cdk.Duration.minutes(1)), });
const role = new iam.Role(this, 'Role', { assumedBy: new iam.ServicePrincipal('events.amazonaws.com') });

// allow EventBridge to use the `publish` mutation
api.grantMutation(role, 'publish');

rule.addTarget(new targets.AppSync(api, {
  graphQLOperation: 'mutation Publish($message: String!){ publish(message: $message) { message } }',
  variables: events.RuleTargetInput.fromObject({
    message: 'hello world',
  }),
  eventRole: role
}));
python
import aws_cdk.aws_iam as iam
import aws_cdk.aws_appsync as appsync


api = appsync.GraphqlApi.from_graphql_api_attributes(self, "ImportedAPI",
    graphql_api_id="<api-id>",
    graphql_api_arn="<api-arn>",
    graph_ql_endpoint_arn="<api-endpoint-arn>",
    visibility=appsync.Visibility.GLOBAL,
    modes=[appsync.AuthorizationType.IAM]
)

rule = events.Rule(self, "Rule", schedule=events.Schedule.rate(cdk.Duration.minutes(1)))
role = iam.Role(self, "Role", assumed_by=iam.ServicePrincipal("events.amazonaws.com"))

# allow EventBridge to use the `publish` mutation
api.grant_mutation(role, "publish")

rule.add_target(targets.AppSync(api,
    graph_ql_operation="mutation Publish($message: String!){ publish(message: $message) { message } }",
    variables=events.RuleTargetInput.from_object({
        "message": "hello world"
    }),
    event_role=role
))
java
import software.amazon.awscdk.services.iam.*;
import software.amazon.awscdk.services.appsync.*;


IGraphqlApi api = GraphqlApi.fromGraphqlApiAttributes(this, "ImportedAPI", GraphqlApiAttributes.builder()
        .graphqlApiId("<api-id>")
        .graphqlApiArn("<api-arn>")
        .graphQLEndpointArn("<api-endpoint-arn>")
        .visibility(Visibility.GLOBAL)
        .modes(List.of(AuthorizationType.IAM))
        .build());

Rule rule = Rule.Builder.create(this, "Rule").schedule(Schedule.rate(Duration.minutes(1))).build();
Role role = Role.Builder.create(this, "Role").assumedBy(new ServicePrincipal("events.amazonaws.com")).build();

// allow EventBridge to use the `publish` mutation
api.grantMutation(role, "publish");

rule.addTarget(AppSync.Builder.create(api)
        .graphQLOperation("mutation Publish($message: String!){ publish(message: $message) { message } }")
        .variables(RuleTargetInput.fromObject(Map.of(
                "message", "hello world")))
        .eventRole(role)
        .build());
csharp
using Amazon.CDK.AWS.IAM;
using Amazon.CDK.AWS.AppSync;


var api = GraphqlApi.FromGraphqlApiAttributes(this, "ImportedAPI", new GraphqlApiAttributes {
    GraphqlApiId = "<api-id>",
    GraphqlApiArn = "<api-arn>",
    GraphQLEndpointArn = "<api-endpoint-arn>",
    Visibility = Visibility.GLOBAL,
    Modes = new [] { AuthorizationType.IAM }
});

var rule = new Rule(this, "Rule", new RuleProps { Schedule = Schedule.Rate(Duration.Minutes(1)) });
var role = new Role(this, "Role", new RoleProps { AssumedBy = new ServicePrincipal("events.amazonaws.com") });

// allow EventBridge to use the `publish` mutation
api.GrantMutation(role, "publish");

rule.AddTarget(new AppSync(api, new AppSyncGraphQLApiProps {
    GraphQLOperation = "mutation Publish($message: String!){ publish(message: $message) { message } }",
    Variables = RuleTargetInput.FromObject(new Dictionary<string, string> {
        { "message", "hello world" }
    }),
    EventRole = role
}));
go
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"


api := appsync.GraphqlApi_FromGraphqlApiAttributes(this, jsii.String("ImportedAPI"), &GraphqlApiAttributes{
	GraphqlApiId: jsii.String("<api-id>"),
	GraphqlApiArn: jsii.String("<api-arn>"),
	GraphQLEndpointArn: jsii.String("<api-endpoint-arn>"),
	Visibility: appsync.Visibility_GLOBAL,
	Modes: []AuthorizationType{
		appsync.AuthorizationType_IAM,
	},
})

rule := events.NewRule(this, jsii.String("Rule"), &RuleProps{
	Schedule: events.Schedule_Rate(cdk.Duration_Minutes(jsii.Number(1))),
})
role := iam.NewRole(this, jsii.String("Role"), &RoleProps{
	AssumedBy: iam.NewServicePrincipal(jsii.String("events.amazonaws.com")),
})

// allow EventBridge to use the `publish` mutation
api.GrantMutation(role, jsii.String("publish"))

rule.AddTarget(targets.NewAppSync(api, &AppSyncGraphQLApiProps{
	GraphQLOperation: jsii.String("mutation Publish($message: String!){ publish(message: $message) { message } }"),
	Variables: events.RuleTargetInput_FromObject(map[string]*string{
		"message": jsii.String("hello world"),
	}),
	EventRole: role,
}))

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.

ts
const rule = new events.Rule(this, 'Rule', {
  schedule: events.Schedule.expression('rate(1 minute)'),
});

rule.addTarget(new targets.EventBus(
  events.EventBus.fromEventBusArn(
    this,
    'External',
    `arn:aws:events:eu-west-1:999999999999:event-bus/test-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")))
java
Rule rule = Rule.Builder.create(this, "Rule")
        .schedule(Schedule.expression("rate(1 minute)"))
        .build();

rule.addTarget(new EventBus(EventBus.fromEventBusArn(this, "External", "arn:aws:events:eu-west-1:999999999999:event-bus/test-bus")));
csharp
var rule = new Rule(this, "Rule", new RuleProps {
    Schedule = Schedule.Expression("rate(1 minute)")
});

rule.AddTarget(new EventBus(EventBus.FromEventBusArn(this, "External", "arn:aws:events:eu-west-1:999999999999:event-bus/test-bus")));
go
rule := events.NewRule(this, jsii.String("Rule"), &RuleProps{
	Schedule: events.Schedule_Expression(jsii.String("rate(1 minute)")),
})

rule.AddTarget(targets.NewEventBus(events.EventBus_FromEventBusArn(this, jsii.String("External"), jsii.String("arn:aws:events:eu-west-1:999999999999:event-bus/test-bus"))))

Put an event on a Firehose delivery stream ​

Use the FirehoseDeliveryStream target to put event to an Amazon Data Firehose delivery stream.

The code snippet below creates the scheduled event rule that put events to an Amazon Data Firehose delivery stream.

ts
import * as firehose from 'aws-cdk-lib/aws-kinesisfirehose';
import * as s3 from 'aws-cdk-lib/aws-s3';

declare const bucket: s3.Bucket;
const stream = new firehose.DeliveryStream(this, 'DeliveryStream', {
  destination: new firehose.S3Bucket(bucket),
});

const rule = new events.Rule(this, 'Rule', {
  schedule: events.Schedule.expression('rate(1 minute)'),
});
rule.addTarget(new targets.FirehoseDeliveryStream(stream));
python
import aws_cdk.aws_kinesisfirehose as firehose
import aws_cdk.aws_s3 as s3

# bucket: s3.Bucket

stream = firehose.DeliveryStream(self, "DeliveryStream",
    destination=firehose.S3Bucket(bucket)
)

rule = events.Rule(self, "Rule",
    schedule=events.Schedule.expression("rate(1 minute)")
)
rule.add_target(targets.FirehoseDeliveryStream(stream))
java
import software.amazon.awscdk.services.kinesisfirehose.*;
import software.amazon.awscdk.services.s3.*;

Bucket bucket;

DeliveryStream stream = DeliveryStream.Builder.create(this, "DeliveryStream")
        .destination(new S3Bucket(bucket))
        .build();

Rule rule = Rule.Builder.create(this, "Rule")
        .schedule(Schedule.expression("rate(1 minute)"))
        .build();
rule.addTarget(new FirehoseDeliveryStream(stream));
csharp
using Amazon.CDK.AWS.KinesisFirehose;
using Amazon.CDK.AWS.S3;

Bucket bucket;

var stream = new DeliveryStream(this, "DeliveryStream", new DeliveryStreamProps {
    Destination = new S3Bucket(bucket)
});

var rule = new Rule(this, "Rule", new RuleProps {
    Schedule = Schedule.Expression("rate(1 minute)")
});
rule.AddTarget(new FirehoseDeliveryStream(stream));
go
import "github.com/aws/aws-cdk-go/awscdk"
import s3 "github.com/aws/aws-cdk-go/awscdk"

var bucket Bucket

stream := firehose.NewDeliveryStream(this, jsii.String("DeliveryStream"), &DeliveryStreamProps{
	Destination: firehose.NewS3Bucket(bucket),
})

rule := events.NewRule(this, jsii.String("Rule"), &RuleProps{
	Schedule: events.Schedule_Expression(jsii.String("rate(1 minute)")),
})
rule.AddTarget(targets.NewFirehoseDeliveryStream(stream))

Run an ECS Task ​

Use the EcsTask target to run an ECS Task.

The code snippet below creates a scheduled event rule that will run the task described in taskDefinition every hour.

Tagging Tasks ​

By default, ECS tasks run from EventBridge targets will not have tags applied to them. You can set the propagateTags field to propagate the tags set on the task definition to the task initialized by the event trigger.

If you want to set tags independent of those applied to the TaskDefinition, you can use the tags array. Both of these fields can be used together or separately to set tags on the triggered task.

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

declare const cluster: ecs.ICluster;
declare const taskDefinition: ecs.TaskDefinition;

const rule = new events.Rule(this, 'Rule', {
  schedule: events.Schedule.rate(cdk.Duration.hours(1)),
});

rule.addTarget(
  new targets.EcsTask({
    cluster: cluster,
    taskDefinition: taskDefinition,
    propagateTags: ecs.PropagatedTagSource.TASK_DEFINITION,
    tags: [
      {
        key: 'my-tag',
        value: 'my-tag-value',
      },
    ],
  }),
);
python
import aws_cdk.aws_ecs as ecs

# cluster: ecs.ICluster
# task_definition: ecs.TaskDefinition


rule = events.Rule(self, "Rule",
    schedule=events.Schedule.rate(cdk.Duration.hours(1))
)

rule.add_target(
    targets.EcsTask(
        cluster=cluster,
        task_definition=task_definition,
        propagate_tags=ecs.PropagatedTagSource.TASK_DEFINITION,
        tags=[targets.Tag(
            key="my-tag",
            value="my-tag-value"
        )
        ]
    ))
java
import software.amazon.awscdk.services.ecs.*;

ICluster cluster;
TaskDefinition taskDefinition;


Rule rule = Rule.Builder.create(this, "Rule")
        .schedule(Schedule.rate(Duration.hours(1)))
        .build();

rule.addTarget(
EcsTask.Builder.create()
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .propagateTags(PropagatedTagSource.TASK_DEFINITION)
        .tags(List.of(Tag.builder()
                .key("my-tag")
                .value("my-tag-value")
                .build()))
        .build());
csharp
using Amazon.CDK.AWS.ECS;

ICluster cluster;
TaskDefinition taskDefinition;


var rule = new Rule(this, "Rule", new RuleProps {
    Schedule = Schedule.Rate(Duration.Hours(1))
});

rule.AddTarget(
new EcsTask(new EcsTaskProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition,
    PropagateTags = PropagatedTagSource.TASK_DEFINITION,
    Tags = new [] { new Tag {
        Key = "my-tag",
        Value = "my-tag-value"
    } }
}));
go
import ecs "github.com/aws/aws-cdk-go/awscdk"

var cluster ICluster
var taskDefinition TaskDefinition


rule := events.NewRule(this, jsii.String("Rule"), &RuleProps{
	Schedule: events.Schedule_Rate(cdk.Duration_Hours(jsii.Number(1))),
})

rule.AddTarget(
targets.NewEcsTask(&EcsTaskProps{
	Cluster: cluster,
	TaskDefinition: taskDefinition,
	PropagateTags: ecs.PropagatedTagSource_TASK_DEFINITION,
	Tags: []Tag{
		&Tag{
			Key: jsii.String("my-tag"),
			Value: jsii.String("my-tag-value"),
		},
	},
}))

Launch type for ECS Task ​

By default, if isEc2Compatible for the taskDefinition is true, the EC2 type is used as the launch type for the task, otherwise the FARGATE type. If you want to override the default launch type, you can set the launchType property.

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

declare const cluster: ecs.ICluster;
declare const taskDefinition: ecs.TaskDefinition;

const rule = new events.Rule(this, 'Rule', {
  schedule: events.Schedule.rate(cdk.Duration.hours(1)),
});

rule.addTarget(new targets.EcsTask({
  cluster,
  taskDefinition,
  launchType: ecs.LaunchType.FARGATE,
}));
python
import aws_cdk.aws_ecs as ecs

# cluster: ecs.ICluster
# task_definition: ecs.TaskDefinition


rule = events.Rule(self, "Rule",
    schedule=events.Schedule.rate(cdk.Duration.hours(1))
)

rule.add_target(targets.EcsTask(
    cluster=cluster,
    task_definition=task_definition,
    launch_type=ecs.LaunchType.FARGATE
))
java
import software.amazon.awscdk.services.ecs.*;

ICluster cluster;
TaskDefinition taskDefinition;


Rule rule = Rule.Builder.create(this, "Rule")
        .schedule(Schedule.rate(Duration.hours(1)))
        .build();

rule.addTarget(EcsTask.Builder.create()
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .launchType(LaunchType.FARGATE)
        .build());
csharp
using Amazon.CDK.AWS.ECS;

ICluster cluster;
TaskDefinition taskDefinition;


var rule = new Rule(this, "Rule", new RuleProps {
    Schedule = Schedule.Rate(Duration.Hours(1))
});

rule.AddTarget(new EcsTask(new EcsTaskProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition,
    LaunchType = LaunchType.FARGATE
}));
go
import ecs "github.com/aws/aws-cdk-go/awscdk"

var cluster ICluster
var taskDefinition TaskDefinition


rule := events.NewRule(this, jsii.String("Rule"), &RuleProps{
	Schedule: events.Schedule_Rate(cdk.Duration_Hours(jsii.Number(1))),
})

rule.AddTarget(targets.NewEcsTask(&EcsTaskProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	LaunchType: ecs.LaunchType_FARGATE,
}))

Assign public IP addresses to tasks ​

You can set the assignPublicIp flag to assign public IP addresses to tasks. If you want to detach the public IP address from the task, you have to set the flag false. You can specify the flag true only when the launch type is set to FARGATE.

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

declare const cluster: ecs.ICluster;
declare const taskDefinition: ecs.TaskDefinition;

const rule = new events.Rule(this, 'Rule', {
  schedule: events.Schedule.rate(cdk.Duration.hours(1)),
});

rule.addTarget(
  new targets.EcsTask({
    cluster,
    taskDefinition,
    assignPublicIp: true,
    subnetSelection: { subnetType: ec2.SubnetType.PUBLIC },
  }),
);
python
import aws_cdk.aws_ecs as ecs
import aws_cdk.aws_ec2 as ec2

# cluster: ecs.ICluster
# task_definition: ecs.TaskDefinition


rule = events.Rule(self, "Rule",
    schedule=events.Schedule.rate(cdk.Duration.hours(1))
)

rule.add_target(
    targets.EcsTask(
        cluster=cluster,
        task_definition=task_definition,
        assign_public_ip=True,
        subnet_selection=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC)
    ))
java
import software.amazon.awscdk.services.ecs.*;
import software.amazon.awscdk.services.ec2.*;

ICluster cluster;
TaskDefinition taskDefinition;


Rule rule = Rule.Builder.create(this, "Rule")
        .schedule(Schedule.rate(Duration.hours(1)))
        .build();

rule.addTarget(
EcsTask.Builder.create()
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .assignPublicIp(true)
        .subnetSelection(SubnetSelection.builder().subnetType(SubnetType.PUBLIC).build())
        .build());
csharp
using Amazon.CDK.AWS.ECS;
using Amazon.CDK.AWS.EC2;

ICluster cluster;
TaskDefinition taskDefinition;


var rule = new Rule(this, "Rule", new RuleProps {
    Schedule = Schedule.Rate(Duration.Hours(1))
});

rule.AddTarget(
new EcsTask(new EcsTaskProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition,
    AssignPublicIp = true,
    SubnetSelection = new SubnetSelection { SubnetType = SubnetType.PUBLIC }
}));
go
import ecs "github.com/aws/aws-cdk-go/awscdk"
import ec2 "github.com/aws/aws-cdk-go/awscdk"

var cluster ICluster
var taskDefinition TaskDefinition


rule := events.NewRule(this, jsii.String("Rule"), &RuleProps{
	Schedule: events.Schedule_Rate(cdk.Duration_Hours(jsii.Number(1))),
})

rule.AddTarget(
targets.NewEcsTask(&EcsTaskProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	AssignPublicIp: jsii.Boolean(true),
	SubnetSelection: &SubnetSelection{
		SubnetType: ec2.SubnetType_PUBLIC,
	},
}))

Enable Amazon ECS Exec for ECS Task ​

If you use Amazon ECS Exec, you can run commands in or get a shell to a container running on an Amazon EC2 instance or on AWS Fargate.

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

declare const cluster: ecs.ICluster;
declare const taskDefinition: ecs.TaskDefinition;

const rule = new events.Rule(this, 'Rule', {
  schedule: events.Schedule.rate(cdk.Duration.hours(1)),
});

rule.addTarget(new targets.EcsTask({
  cluster,
  taskDefinition,
  taskCount: 1,
  containerOverrides: [{
    containerName: 'TheContainer',
    command: ['echo', events.EventField.fromPath('$.detail.event')],
  }],
  enableExecuteCommand: true,
}));
python
import aws_cdk.aws_ecs as ecs

# cluster: ecs.ICluster
# task_definition: ecs.TaskDefinition


rule = events.Rule(self, "Rule",
    schedule=events.Schedule.rate(cdk.Duration.hours(1))
)

rule.add_target(targets.EcsTask(
    cluster=cluster,
    task_definition=task_definition,
    task_count=1,
    container_overrides=[targets.ContainerOverride(
        container_name="TheContainer",
        command=["echo", events.EventField.from_path("$.detail.event")]
    )],
    enable_execute_command=True
))
java
import software.amazon.awscdk.services.ecs.*;

ICluster cluster;
TaskDefinition taskDefinition;


Rule rule = Rule.Builder.create(this, "Rule")
        .schedule(Schedule.rate(Duration.hours(1)))
        .build();

rule.addTarget(EcsTask.Builder.create()
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .taskCount(1)
        .containerOverrides(List.of(ContainerOverride.builder()
                .containerName("TheContainer")
                .command(List.of("echo", EventField.fromPath("$.detail.event")))
                .build()))
        .enableExecuteCommand(true)
        .build());
csharp
using Amazon.CDK.AWS.ECS;

ICluster cluster;
TaskDefinition taskDefinition;


var rule = new Rule(this, "Rule", new RuleProps {
    Schedule = Schedule.Rate(Duration.Hours(1))
});

rule.AddTarget(new EcsTask(new EcsTaskProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition,
    TaskCount = 1,
    ContainerOverrides = new [] { new ContainerOverride {
        ContainerName = "TheContainer",
        Command = new [] { "echo", EventField.FromPath("$.detail.event") }
    } },
    EnableExecuteCommand = true
}));
go
import ecs "github.com/aws/aws-cdk-go/awscdk"

var cluster ICluster
var taskDefinition TaskDefinition


rule := events.NewRule(this, jsii.String("Rule"), &RuleProps{
	Schedule: events.Schedule_Rate(cdk.Duration_Hours(jsii.Number(1))),
})

rule.AddTarget(targets.NewEcsTask(&EcsTaskProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	TaskCount: jsii.Number(1),
	ContainerOverrides: []ContainerOverride{
		&ContainerOverride{
			ContainerName: jsii.String("TheContainer"),
			Command: []*string{
				jsii.String("echo"),
				events.EventField_FromPath(jsii.String("$.detail.event")),
			},
		},
	},
	EnableExecuteCommand: jsii.Boolean(true),
}))

Overriding Values in the Task Definition ​

You can override values in the task definition by setting the corresponding properties in the EcsTaskProps. All values in the TaskOverrides API are supported.

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

declare const cluster: ecs.ICluster;
declare const taskDefinition: ecs.TaskDefinition;

const rule = new events.Rule(this, 'Rule', {
  schedule: events.Schedule.rate(cdk.Duration.hours(1)),
});

rule.addTarget(new targets.EcsTask({
  cluster,
  taskDefinition,
  taskCount: 1,

  // Overrides the cpu and memory values in the task definition
  cpu: '512',
  memory: '512',
}));
python
import aws_cdk.aws_ecs as ecs

# cluster: ecs.ICluster
# task_definition: ecs.TaskDefinition


rule = events.Rule(self, "Rule",
    schedule=events.Schedule.rate(cdk.Duration.hours(1))
)

rule.add_target(targets.EcsTask(
    cluster=cluster,
    task_definition=task_definition,
    task_count=1,

    # Overrides the cpu and memory values in the task definition
    cpu="512",
    memory="512"
))
java
import software.amazon.awscdk.services.ecs.*;

ICluster cluster;
TaskDefinition taskDefinition;


Rule rule = Rule.Builder.create(this, "Rule")
        .schedule(Schedule.rate(Duration.hours(1)))
        .build();

rule.addTarget(EcsTask.Builder.create()
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .taskCount(1)

        // Overrides the cpu and memory values in the task definition
        .cpu("512")
        .memory("512")
        .build());
csharp
using Amazon.CDK.AWS.ECS;

ICluster cluster;
TaskDefinition taskDefinition;


var rule = new Rule(this, "Rule", new RuleProps {
    Schedule = Schedule.Rate(Duration.Hours(1))
});

rule.AddTarget(new EcsTask(new EcsTaskProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition,
    TaskCount = 1,

    // Overrides the cpu and memory values in the task definition
    Cpu = "512",
    Memory = "512"
}));
go
import ecs "github.com/aws/aws-cdk-go/awscdk"

var cluster ICluster
var taskDefinition TaskDefinition


rule := events.NewRule(this, jsii.String("Rule"), &RuleProps{
	Schedule: events.Schedule_Rate(cdk.Duration_Hours(jsii.Number(1))),
})

rule.AddTarget(targets.NewEcsTask(&EcsTaskProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	TaskCount: jsii.Number(1),

	// Overrides the cpu and memory values in the task definition
	Cpu: jsii.String("512"),
	Memory: jsii.String("512"),
}))

Schedule a Redshift query (serverless or cluster) ​

Use the RedshiftQuery target to schedule an Amazon Redshift Query.

The code snippet below creates the scheduled event rule that route events to an Amazon Redshift Query

ts
import * as redshiftserverless from 'aws-cdk-lib/aws-redshiftserverless'

declare const workgroup: redshiftserverless.CfnWorkgroup;

const rule = new events.Rule(this, 'Rule', {
  schedule: events.Schedule.rate(cdk.Duration.hours(1)),
});

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

rule.addTarget(new targets.RedshiftQuery(workgroup.attrWorkgroupWorkgroupArn, {
  database: 'dev',
  deadLetterQueue: dlq,
  sql: ['SELECT * FROM foo','SELECT * FROM baz'],
}));
python
import aws_cdk.aws_redshiftserverless as redshiftserverless

# workgroup: redshiftserverless.CfnWorkgroup


rule = events.Rule(self, "Rule",
    schedule=events.Schedule.rate(cdk.Duration.hours(1))
)

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

rule.add_target(targets.RedshiftQuery(workgroup.attr_workgroup_workgroup_arn,
    database="dev",
    dead_letter_queue=dlq,
    sql=["SELECT * FROM foo", "SELECT * FROM baz"]
))
java
import software.amazon.awscdk.services.redshiftserverless.*;

CfnWorkgroup workgroup;


Rule rule = Rule.Builder.create(this, "Rule")
        .schedule(Schedule.rate(Duration.hours(1)))
        .build();

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

rule.addTarget(RedshiftQuery.Builder.create(workgroup.getAttrWorkgroupWorkgroupArn())
        .database("dev")
        .deadLetterQueue(dlq)
        .sql(List.of("SELECT * FROM foo", "SELECT * FROM baz"))
        .build());
csharp
using Amazon.CDK.AWS.RedshiftServerless;

CfnWorkgroup workgroup;


var rule = new Rule(this, "Rule", new RuleProps {
    Schedule = Schedule.Rate(Duration.Hours(1))
});

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

rule.AddTarget(new RedshiftQuery(workgroup.AttrWorkgroupWorkgroupArn, new RedshiftQueryProps {
    Database = "dev",
    DeadLetterQueue = dlq,
    Sql = new [] { "SELECT * FROM foo", "SELECT * FROM baz" }
}));
go
import redshiftserverless "github.com/aws/aws-cdk-go/awscdk"

var workgroup CfnWorkgroup


rule := events.NewRule(this, jsii.String("Rule"), &RuleProps{
	Schedule: events.Schedule_Rate(cdk.Duration_Hours(jsii.Number(1))),
})

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

rule.AddTarget(targets.NewRedshiftQuery(workgroup.attrWorkgroupWorkgroupArn, &RedshiftQueryProps{
	Database: jsii.String("dev"),
	DeadLetterQueue: dlq,
	Sql: []*string{
		jsii.String("SELECT * FROM foo"),
		jsii.String("SELECT * FROM baz"),
	},
}))

Send events to an SQS queue ​

Use the SqsQueue target to send events to an SQS queue.

The code snippet below creates an event rule that sends events to an SQS queue every hour:

ts
const queue = new sqs.Queue(this, 'MyQueue');

const rule = new events.Rule(this, 'Rule', {
  schedule: events.Schedule.rate(cdk.Duration.hours(1)),
});

rule.addTarget(new targets.SqsQueue(queue));
python
queue = sqs.Queue(self, "MyQueue")

rule = events.Rule(self, "Rule",
    schedule=events.Schedule.rate(cdk.Duration.hours(1))
)

rule.add_target(targets.SqsQueue(queue))
java
Queue queue = new Queue(this, "MyQueue");

Rule rule = Rule.Builder.create(this, "Rule")
        .schedule(Schedule.rate(Duration.hours(1)))
        .build();

rule.addTarget(new SqsQueue(queue));
csharp
var queue = new Queue(this, "MyQueue");

var rule = new Rule(this, "Rule", new RuleProps {
    Schedule = Schedule.Rate(Duration.Hours(1))
});

rule.AddTarget(new SqsQueue(queue));
go
queue := sqs.NewQueue(this, jsii.String("MyQueue"))

rule := events.NewRule(this, jsii.String("Rule"), &RuleProps{
	Schedule: events.Schedule_Rate(cdk.Duration_Hours(jsii.Number(1))),
})

rule.AddTarget(targets.NewSqsQueue(queue))

Using Message Group IDs ​

You can specify a messageGroupId to ensure messages are processed in order. This parameter is required for FIFO queues and optional for standard queues:

ts
// FIFO queue - messageGroupId required
const fifoQueue = new sqs.Queue(this, 'MyFifoQueue', {
  fifo: true,
});

const fifoRule = new events.Rule(this, 'FifoRule', {
  schedule: events.Schedule.rate(cdk.Duration.hours(1)),
});

fifoRule.addTarget(new targets.SqsQueue(fifoQueue, {
  messageGroupId: 'MyMessageGroupId',
}));

// Standard queue - messageGroupId optional (SQS Fair queue feature)
const standardQueue = new sqs.Queue(this, 'MyStandardQueue');

const standardRule = new events.Rule(this, 'StandardRule', {
  schedule: events.Schedule.rate(cdk.Duration.hours(1)),
});

standardRule.addTarget(new targets.SqsQueue(standardQueue, {
  messageGroupId: 'MyMessageGroupId', // Optional for standard queues
}));
python
# FIFO queue - messageGroupId required
fifo_queue = sqs.Queue(self, "MyFifoQueue",
    fifo=True
)

fifo_rule = events.Rule(self, "FifoRule",
    schedule=events.Schedule.rate(cdk.Duration.hours(1))
)

fifo_rule.add_target(targets.SqsQueue(fifo_queue,
    message_group_id="MyMessageGroupId"
))

# Standard queue - messageGroupId optional (SQS Fair queue feature)
standard_queue = sqs.Queue(self, "MyStandardQueue")

standard_rule = events.Rule(self, "StandardRule",
    schedule=events.Schedule.rate(cdk.Duration.hours(1))
)

standard_rule.add_target(targets.SqsQueue(standard_queue,
    message_group_id="MyMessageGroupId"
))
java
// FIFO queue - messageGroupId required
Queue fifoQueue = Queue.Builder.create(this, "MyFifoQueue")
        .fifo(true)
        .build();

Rule fifoRule = Rule.Builder.create(this, "FifoRule")
        .schedule(Schedule.rate(Duration.hours(1)))
        .build();

fifoRule.addTarget(SqsQueue.Builder.create(fifoQueue)
        .messageGroupId("MyMessageGroupId")
        .build());

// Standard queue - messageGroupId optional (SQS Fair queue feature)
Queue standardQueue = new Queue(this, "MyStandardQueue");

Rule standardRule = Rule.Builder.create(this, "StandardRule")
        .schedule(Schedule.rate(Duration.hours(1)))
        .build();

standardRule.addTarget(SqsQueue.Builder.create(standardQueue)
        .messageGroupId("MyMessageGroupId")
        .build());
csharp
// FIFO queue - messageGroupId required
var fifoQueue = new Queue(this, "MyFifoQueue", new QueueProps {
    Fifo = true
});

var fifoRule = new Rule(this, "FifoRule", new RuleProps {
    Schedule = Schedule.Rate(Duration.Hours(1))
});

fifoRule.AddTarget(new SqsQueue(fifoQueue, new SqsQueueProps {
    MessageGroupId = "MyMessageGroupId"
}));

// Standard queue - messageGroupId optional (SQS Fair queue feature)
var standardQueue = new Queue(this, "MyStandardQueue");

var standardRule = new Rule(this, "StandardRule", new RuleProps {
    Schedule = Schedule.Rate(Duration.Hours(1))
});

standardRule.AddTarget(new SqsQueue(standardQueue, new SqsQueueProps {
    MessageGroupId = "MyMessageGroupId"
}));
go
// FIFO queue - messageGroupId required
fifoQueue := sqs.NewQueue(this, jsii.String("MyFifoQueue"), &QueueProps{
	Fifo: jsii.Boolean(true),
})

fifoRule := events.NewRule(this, jsii.String("FifoRule"), &RuleProps{
	Schedule: events.Schedule_Rate(cdk.Duration_Hours(jsii.Number(1))),
})

fifoRule.AddTarget(targets.NewSqsQueue(fifoQueue, &SqsQueueProps{
	MessageGroupId: jsii.String("MyMessageGroupId"),
}))

// Standard queue - messageGroupId optional (SQS Fair queue feature)
standardQueue := sqs.NewQueue(this, jsii.String("MyStandardQueue"))

standardRule := events.NewRule(this, jsii.String("StandardRule"), &RuleProps{
	Schedule: events.Schedule_*Rate(cdk.Duration_*Hours(jsii.Number(1))),
})

standardRule.AddTarget(targets.NewSqsQueue(standardQueue, &SqsQueueProps{
	MessageGroupId: jsii.String("MyMessageGroupId"),
}))

Publish to an SNS Topic ​

Use the SnsTopic target to publish to an SNS Topic.

The code snippet below creates the scheduled event rule that publishes to an SNS Topic using a resource policy.

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

declare const topic: sns.ITopic;

const rule = new events.Rule(this, 'Rule', {
  schedule: events.Schedule.rate(cdk.Duration.hours(1)),
});

rule.addTarget(new targets.SnsTopic(topic));
python
import aws_cdk.aws_sns as sns

# topic: sns.ITopic


rule = events.Rule(self, "Rule",
    schedule=events.Schedule.rate(cdk.Duration.hours(1))
)

rule.add_target(targets.SnsTopic(topic))
java
import software.amazon.awscdk.services.sns.*;

ITopic topic;


Rule rule = Rule.Builder.create(this, "Rule")
        .schedule(Schedule.rate(Duration.hours(1)))
        .build();

rule.addTarget(new SnsTopic(topic));
csharp
using Amazon.CDK.AWS.SNS;

ITopic topic;


var rule = new Rule(this, "Rule", new RuleProps {
    Schedule = Schedule.Rate(Duration.Hours(1))
});

rule.AddTarget(new SnsTopic(topic));
go
import sns "github.com/aws/aws-cdk-go/awscdk"

var topic ITopic


rule := events.NewRule(this, jsii.String("Rule"), &RuleProps{
	Schedule: events.Schedule_Rate(cdk.Duration_Hours(jsii.Number(1))),
})

rule.AddTarget(targets.NewSnsTopic(topic))

Alternatively, a role can be attached to the target when the rule is triggered.

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

declare const topic: sns.ITopic;

const rule = new events.Rule(this, 'Rule', {
  schedule: events.Schedule.rate(cdk.Duration.hours(1)),
});

rule.addTarget(new targets.SnsTopic(topic, { authorizeUsingRole: true }));
python
import aws_cdk.aws_sns as sns

# topic: sns.ITopic


rule = events.Rule(self, "Rule",
    schedule=events.Schedule.rate(cdk.Duration.hours(1))
)

rule.add_target(targets.SnsTopic(topic, authorize_using_role=True))
java
import software.amazon.awscdk.services.sns.*;

ITopic topic;


Rule rule = Rule.Builder.create(this, "Rule")
        .schedule(Schedule.rate(Duration.hours(1)))
        .build();

rule.addTarget(SnsTopic.Builder.create(topic).authorizeUsingRole(true).build());
csharp
using Amazon.CDK.AWS.SNS;

ITopic topic;


var rule = new Rule(this, "Rule", new RuleProps {
    Schedule = Schedule.Rate(Duration.Hours(1))
});

rule.AddTarget(new SnsTopic(topic, new SnsTopicProps { AuthorizeUsingRole = true }));
go
import sns "github.com/aws/aws-cdk-go/awscdk"

var topic ITopic


rule := events.NewRule(this, jsii.String("Rule"), &RuleProps{
	Schedule: events.Schedule_Rate(cdk.Duration_Hours(jsii.Number(1))),
})

rule.AddTarget(targets.NewSnsTopic(topic, &SnsTopicProps{
	AuthorizeUsingRole: jsii.Boolean(true),
}))

Types ​

NameKindSummary
ApiDestinationClassUse an API Destination rule target.
ApiDestinationPropsStructCustomize the EventBridge Api Destinations Target.
ApiGatewayClassUse an API Gateway REST APIs as a target for Amazon EventBridge rules.
ApiGatewayPropsStructCustomize the API Gateway Event Target.
ApiGatewayV2ClassUse an API Gateway V2 HTTP APIs as a target for Amazon EventBridge rules.
AppSyncClassUse an AppSync GraphQL API as a target for Amazon EventBridge rules.
AppSyncGraphQLApiPropsStructCustomize the AppSync GraphQL API target.
AwsApiClassUse an AWS Lambda function that makes API calls as an event rule target.
AwsApiInputStructRule target input for an AwsApi target.
AwsApiPropsStructProperties for an AwsApi target.
BatchJobClassUse an AWS Batch Job / Queue as an event rule target.
BatchJobPropsStructCustomize the Batch Job Event Target.
CloudWatchLogGroupClassUse an AWS CloudWatch LogGroup as an event rule target.
CodeBuildProjectClassStart a CodeBuild build when an Amazon EventBridge rule is triggered.
CodeBuildProjectPropsStructCustomize the CodeBuild Event Target.
CodePipelineClassAllows the pipeline to be used as an EventBridge rule target.
CodePipelineTargetOptionsStructCustomization options when creating a CodePipeline event target.
ContainerOverrideStruct
EcsTaskClassStart a task on an ECS cluster.
EcsTaskPropsStructProperties to define an ECS Event Task.
EphemeralStorageOverrideStructOverride ephemeral storage for the task.
EventBusClassNotify an existing Event Bus of an event.
EventBusPropsStructConfiguration properties of an Event Bus event.
FirehoseDeliveryStreamClassCustomize the Amazon Data Firehose Stream Event Target.
FirehoseDeliveryStreamPropsStructCustomize the Amazon Data Firehose Stream Event Target.
IDeliveryStreamInterfaceRepresents an Amazon Data Firehose delivery stream.
InferenceAcceleratorOverrideStructOverride inference accelerators for the task.
KinesisFirehoseStreamClassCustomize the Amazon Data Firehose Stream Event Target.
KinesisFirehoseStreamPropsStructCustomize the Amazon Data Firehose Stream Event Target.
KinesisFirehoseStreamV2ClassCustomize the Amazon Data Firehose Stream Event Target V2 to support L2 Amazon Data Firehose Delivery Stream instead of L1 Cfn Firehose Delivery Stream.
KinesisStreamClassUse a Kinesis Stream as a target for AWS CloudWatch event rules.
KinesisStreamPropsStructCustomize the Kinesis Stream Event Target.
LambdaFunctionClassUse an AWS Lambda function as an event rule target.
LambdaFunctionPropsStructCustomize the Lambda Event Target.
LogGroupPropsStructCustomize the CloudWatch LogGroup Event Target.
LogGroupTargetInputClassThe input to send to the CloudWatch LogGroup target.
LogGroupTargetInputOptionsStructOptions used when creating a target input template.
RedshiftQueryClassSchedule an Amazon Redshift Query to be run, using the Redshift Data API.
RedshiftQueryPropsStructConfiguration properties of an Amazon Redshift Query event.
SfnStateMachineClassUse a StepFunctions state machine as a target for Amazon EventBridge rules.
SfnStateMachinePropsStructCustomize the Step Functions State Machine target.
SnsTopicClassUse an SNS topic as a target for Amazon EventBridge rules.
SnsTopicPropsStructCustomize the SNS Topic Event Target.
SqsQueueClassUse an SQS Queue as a target for Amazon EventBridge rules.
SqsQueuePropsStructCustomize the SQS Queue Event Target.
TagStructMetadata that you apply to a resource to help categorize and organize the resource.
TargetBasePropsStructThe generic properties for an RuleTarget.
TaskEnvironmentVariableStructAn environment variable to be set in the container run as a task.