Namespace Amazon.CDK.AWS.Events.Targets
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, 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.
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
}));
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.
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));
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.
using Amazon.CDK.AWS.Logs;
LogGroup logGroup;
Rule rule;
rule.AddTarget(new CloudWatchLogGroup(logGroup, new LogGroupProps {
LogEvent = LogGroupTargetInput.FromObject(new LogGroupTargetInputOptions {
Timestamp = EventField.FromPath("$.time"),
Message = EventField.FromPath("$.detail-type")
})
}));
If you want to use static values to overwrite the message
make sure that you provide a string
value.
using Amazon.CDK.AWS.Logs;
LogGroup logGroup;
Rule rule;
rule.AddTarget(new CloudWatchLogGroup(logGroup, new LogGroupProps {
LogEvent = LogGroupTargetInput.FromObject(new LogGroupTargetInputOptions {
Message = JSON.Stringify(new Dictionary<string, string> {
{ "CustomField", "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
.
using Amazon.CDK.AWS.Logs;
LogGroup logGroup;
Rule rule;
rule.AddTarget(new CloudWatchLogGroup(logGroup, new LogGroupProps {
InstallLatestAwsSdk = 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.
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" }
});
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
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));
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.
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
}));
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.
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)
}));
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.
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
}));
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.
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) }
});
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.
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")));
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.
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"
} }
}));
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.
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
}));
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.
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 }
}));
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.
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
}));
Classes
ApiDestination | Use an API Destination rule target. |
ApiDestinationProps | Customize the EventBridge Api Destinations Target. |
ApiGateway | Use an API Gateway REST APIs as a target for Amazon EventBridge rules. |
ApiGatewayProps | Customize the API Gateway Event Target. |
AwsApi | Use an AWS Lambda function that makes API calls as an event rule target. |
AwsApiInput | Rule target input for an AwsApi target. |
AwsApiProps | Properties for an AwsApi target. |
BatchJob | Use an AWS Batch Job / Queue as an event rule target. |
BatchJobProps | Customize the Batch Job Event Target. |
CloudWatchLogGroup | Use an AWS CloudWatch LogGroup as an event rule target. |
CodeBuildProject | Start a CodeBuild build when an Amazon EventBridge rule is triggered. |
CodeBuildProjectProps | Customize the CodeBuild Event Target. |
CodePipeline | Allows the pipeline to be used as an EventBridge rule target. |
CodePipelineTargetOptions | Customization options when creating a |
ContainerOverride | |
EcsTask | Start a task on an ECS cluster. |
EcsTaskProps | Properties to define an ECS Event Task. |
EventBus | Notify an existing Event Bus of an event. |
EventBusProps | Configuration properties of an Event Bus event. |
KinesisFirehoseStream | Customize the Firehose Stream Event Target. |
KinesisFirehoseStreamProps | Customize the Firehose Stream Event Target. |
KinesisStream | Use a Kinesis Stream as a target for AWS CloudWatch event rules. |
KinesisStreamProps | Customize the Kinesis Stream Event Target. |
LambdaFunction | Use an AWS Lambda function as an event rule target. |
LambdaFunctionProps | Customize the Lambda Event Target. |
LogGroupProps | Customize the CloudWatch LogGroup Event Target. |
LogGroupTargetInput | The input to send to the CloudWatch LogGroup target. |
LogGroupTargetInputOptions | Options used when creating a target input template. |
SfnStateMachine | Use a StepFunctions state machine as a target for Amazon EventBridge rules. |
SfnStateMachineProps | Customize the Step Functions State Machine target. |
SnsTopic | Use an SNS topic as a target for Amazon EventBridge rules. |
SnsTopicProps | Customize the SNS Topic Event Target. |
SqsQueue | Use an SQS Queue as a target for Amazon EventBridge rules. |
SqsQueueProps | Customize the SQS Queue Event Target. |
Tag | Metadata that you apply to a resource to help categorize and organize the resource. |
TargetBaseProps | The generic properties for an RuleTarget. |
TaskEnvironmentVariable | An environment variable to be set in the container run as a task. |
Interfaces
IApiDestinationProps | Customize the EventBridge Api Destinations Target. |
IApiGatewayProps | Customize the API Gateway Event Target. |
IAwsApiInput | Rule target input for an AwsApi target. |
IAwsApiProps | Properties for an AwsApi target. |
IBatchJobProps | Customize the Batch Job Event Target. |
ICodeBuildProjectProps | Customize the CodeBuild Event Target. |
ICodePipelineTargetOptions | Customization options when creating a |
IContainerOverride | |
IEcsTaskProps | Properties to define an ECS Event Task. |
IEventBusProps | Configuration properties of an Event Bus event. |
IKinesisFirehoseStreamProps | Customize the Firehose Stream Event Target. |
IKinesisStreamProps | Customize the Kinesis Stream Event Target. |
ILambdaFunctionProps | Customize the Lambda Event Target. |
ILogGroupProps | Customize the CloudWatch LogGroup Event Target. |
ILogGroupTargetInputOptions | Options used when creating a target input template. |
ISfnStateMachineProps | Customize the Step Functions State Machine target. |
ISnsTopicProps | Customize the SNS Topic Event Target. |
ISqsQueueProps | Customize the SQS Queue Event Target. |
ITag | Metadata that you apply to a resource to help categorize and organize the resource. |
ITargetBaseProps | The generic properties for an RuleTarget. |
ITaskEnvironmentVariable | An environment variable to be set in the container run as a task. |