CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-aws-cdk--aws-events-targets

Event targets for Amazon EventBridge that enable routing events to various AWS services

Overview
Eval results
Files

compute-targets.mddocs/

Compute Targets

Targets for compute services that can execute code or run workloads in response to EventBridge events.

Capabilities

Lambda Function Target

Execute AWS Lambda functions in response to EventBridge events.

/**
 * Use an AWS Lambda function as an event rule target
 */
class LambdaFunction implements events.IRuleTarget {
  constructor(handler: lambda.IFunction, props?: LambdaFunctionProps);
  
  /**
   * Returns a RuleTarget that can be used to trigger this Lambda function
   * as a result from an EventBridge event
   */
  bind(rule: events.IRule, id?: string): events.RuleTargetConfig;
}

interface LambdaFunctionProps extends TargetBaseProps {
  /**
   * The event to send to the Lambda function
   * This will be the payload sent to the Lambda Function
   * @default the entire EventBridge event
   */
  readonly event?: events.RuleTargetInput;
}

Usage Example:

import * as lambda from "@aws-cdk/aws-lambda";
import * as events from "@aws-cdk/aws-events";
import * as targets from "@aws-cdk/aws-events-targets";
import * as sqs from "@aws-cdk/aws-sqs";

// Create Lambda function
const fn = new lambda.Function(this, "MyFunc", {
  runtime: lambda.Runtime.NODEJS_14_X,
  handler: "index.handler",
  code: lambda.Code.fromInline("exports.handler = async (event) => console.log(event)"),
});

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

// Create dead letter queue for failed invocations
const dlq = new sqs.Queue(this, "DeadLetterQueue");

// Add Lambda target with error handling
rule.addTarget(new targets.LambdaFunction(fn, {
  deadLetterQueue: dlq,
  maxEventAge: Duration.hours(2),
  retryAttempts: 2,
  event: events.RuleTargetInput.fromObject({
    timestamp: events.EventField.fromPath("$.time"),
    source: events.EventField.fromPath("$.source"),
  }),
}));

ECS Task Target

Run Amazon ECS tasks in response to EventBridge events.

/**
 * Use Amazon ECS tasks as EventBridge targets
 */
class EcsTask implements events.IRuleTarget {
  /** Deprecated security group property */
  readonly securityGroup?: ec2.ISecurityGroup;
  /** Security groups for task network interfaces */
  readonly securityGroups?: ec2.ISecurityGroup[];
  
  constructor(props: EcsTaskProps);
  
  /**
   * Returns a RuleTarget that can be used to run this ECS task
   * as a result from an EventBridge event
   */
  bind(rule: events.IRule, id?: string): events.RuleTargetConfig;
}

interface EcsTaskProps {
  /** ECS cluster to run the task on */
  readonly cluster: ecs.ICluster;
  /** Task definition to use for the task */
  readonly taskDefinition: ecs.ITaskDefinition;
  /** Number of tasks to start */
  readonly taskCount?: number;
  /** Container overrides for the task */
  readonly containerOverrides?: ContainerOverride[];
  /** Subnet selection for task network interfaces */
  readonly subnetSelection?: ec2.SubnetSelection;
  /** Security group for task network interfaces (deprecated) */
  readonly securityGroup?: ec2.ISecurityGroup;
  /** Security groups for task network interfaces */
  readonly securityGroups?: ec2.ISecurityGroup[];
  /** IAM role to run the ECS task */
  readonly role?: iam.IRole;
  /** Platform version for Fargate tasks */
  readonly platformVersion?: ecs.FargatePlatformVersion;
}

Usage Example:

import * as ecs from "@aws-cdk/aws-ecs";
import * as ec2 from "@aws-cdk/aws-ec2";
import * as events from "@aws-cdk/aws-events";
import * as targets from "@aws-cdk/aws-events-targets";

// Create VPC and cluster
const vpc = new ec2.Vpc(this, "VPC");
const cluster = new ecs.Cluster(this, "Cluster", { vpc });

// Create task definition
const taskDef = new ecs.FargateTaskDefinition(this, "TaskDef");
taskDef.addContainer("container", {
  image: ecs.ContainerImage.fromRegistry("nginx"),
  memoryLimitMiB: 256,
});

// Create rule to trigger on S3 object creation
const rule = new events.Rule(this, "S3Rule", {
  eventPattern: {
    source: ["aws.s3"],
    detailType: ["Object Created"],
  },
});

// Add ECS task target with container overrides
rule.addTarget(new targets.EcsTask({
  cluster,
  taskDefinition: taskDef,
  taskCount: 1,
  containerOverrides: [{
    containerName: "container",
    environment: [{
      name: "S3_BUCKET",
      value: events.EventField.fromPath("$.detail.bucket.name"),
    }],
  }],
  subnetSelection: { subnetType: ec2.SubnetType.PRIVATE },
}));

Batch Job Target

Queue AWS Batch jobs in response to EventBridge events.

/**
 * Use an AWS Batch Job / Queue as an event rule target
 */
class BatchJob implements events.IRuleTarget {
  constructor(
    /** The JobQueue ARN */
    jobQueueArn: string,
    /** The JobQueue Resource */
    jobQueueScope: IConstruct,
    /** The jobDefinition ARN */
    jobDefinitionArn: string,
    /** The JobDefinition Resource */
    jobDefinitionScope: IConstruct,
    props?: BatchJobProps
  );
  
  /**
   * Returns a RuleTarget that can be used to queue this batch job
   * as a result from an EventBridge event
   */
  bind(rule: events.IRule, id?: string): events.RuleTargetConfig;
}

interface BatchJobProps extends TargetBaseProps {
  /**
   * The event to send to the Batch job
   * This will be the payload sent to the job
   * @default the entire EventBridge event
   */
  readonly event?: events.RuleTargetInput;
  
  /**
   * The size of the array, if this is an array batch job
   * Valid values are integers between 2 and 10,000
   * @default no arrayProperties are set
   */
  readonly size?: number;
  
  /**
   * The number of times to attempt to retry, if the job fails
   * Valid values are 1–10
   * @default no retryStrategy is set
   */
  readonly attempts?: number;
  
  /**
   * The name of the submitted job
   * @default Automatically generated
   */
  readonly jobName?: string;
}

Usage Example:

import * as batch from "@aws-cdk/aws-batch";
import * as ec2 from "@aws-cdk/aws-ec2";
import * as ecs from "@aws-cdk/aws-ecs";
import * as events from "@aws-cdk/aws-events";
import * as targets from "@aws-cdk/aws-events-targets";
import * as sqs from "@aws-cdk/aws-sqs";

// Create Batch resources
const vpc = new ec2.Vpc(this, "VPC");
const computeEnvironment = new batch.ComputeEnvironment(this, "ComputeEnv", {
  managed: false,
});

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

const jobDefinition = new batch.JobDefinition(this, "JobDef", {
  container: {
    image: ecs.ContainerImage.fromRegistry("busybox"),
    vcpus: 1,
    memoryLimitMiB: 512,
  },
});

// Create rule for scheduled execution
const rule = new events.Rule(this, "ScheduledRule", {
  schedule: events.Schedule.rate(Duration.hours(1)),
});

// Create dead letter queue
const dlq = new sqs.Queue(this, "DeadLetterQueue");

// Add Batch job target
rule.addTarget(new targets.BatchJob(
  jobQueue.jobQueueArn,
  jobQueue,
  jobDefinition.jobDefinitionArn,
  jobDefinition,
  {
    deadLetterQueue: dlq,
    event: events.RuleTargetInput.fromObject({
      timestamp: events.EventField.fromPath("$.time"),
      jobData: "scheduled-processing",
    }),
    retryAttempts: 2,
    maxEventAge: Duration.hours(2),
    jobName: "scheduled-data-processing",
  }
));

Container Override Configuration

interface ContainerOverride {
  /** Name of the container inside the task definition */
  readonly containerName: string;
  /** Command to run inside the container */
  readonly command?: string[];
  /** Variables to set in the container's environment */
  readonly environment?: TaskEnvironmentVariable[];
  /** The number of cpu units reserved for the container */
  readonly cpu?: number;
  /** Hard memory limit on the container */
  readonly memoryLimit?: number;
  /** Soft memory limit on the container */
  readonly memoryReservation?: number;
}

interface TaskEnvironmentVariable {
  /** Name for the environment variable */
  readonly name: string;
  /** Value of the environment variable */
  readonly value: string;
}

Install with Tessl CLI

npx tessl i tessl/npm-aws-cdk--aws-events-targets

docs

analytics-targets.md

api-targets.md

cicd-targets.md

compute-targets.md

index.md

messaging-targets.md

orchestration-targets.md

system-targets.md

tile.json