Socket
Socket
Sign inDemoInstall

@aws-cdk/aws-events

Package Overview
Dependencies
Maintainers
5
Versions
288
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@aws-cdk/aws-events

Amazon EventBridge Construct Library


Version published
Weekly downloads
154K
increased by30.35%
Maintainers
5
Weekly downloads
 
Created

Package description

What is @aws-cdk/aws-events?

@aws-cdk/aws-events is an AWS Cloud Development Kit (CDK) library that allows you to define and manage Amazon EventBridge resources using code. EventBridge is a serverless event bus that makes it easier to build event-driven applications by connecting application data from your own applications, integrated Software-as-a-Service (SaaS) applications, and AWS services.

What are @aws-cdk/aws-events's main functionalities?

Creating an Event Bus

This code sample demonstrates how to create a new EventBridge event bus using the AWS CDK. The event bus can be used to receive and route events.

const events = require('@aws-cdk/aws-events');
const cdk = require('@aws-cdk/core');

const app = new cdk.App();
const stack = new cdk.Stack(app, 'EventBusStack');

const eventBus = new events.EventBus(stack, 'MyEventBus', {
  eventBusName: 'my-event-bus'
});

app.synth();

Creating a Rule

This code sample demonstrates how to create an EventBridge rule that triggers when an EC2 instance changes state to 'running'. The rule targets a Lambda function.

const events = require('@aws-cdk/aws-events');
const targets = require('@aws-cdk/aws-events-targets');
const cdk = require('@aws-cdk/core');

const app = new cdk.App();
const stack = new cdk.Stack(app, 'EventRuleStack');

const rule = new events.Rule(stack, 'MyRule', {
  eventPattern: {
    source: ['aws.ec2'],
    detailType: ['EC2 Instance State-change Notification'],
    detail: {
      state: ['running']
    }
  }
});

rule.addTarget(new targets.LambdaFunction(myLambdaFunction));

app.synth();

Scheduling Events

This code sample demonstrates how to create a scheduled EventBridge rule that triggers every 5 minutes. The rule targets a Lambda function.

const events = require('@aws-cdk/aws-events');
const targets = require('@aws-cdk/aws-events-targets');
const cdk = require('@aws-cdk/core');

const app = new cdk.App();
const stack = new cdk.Stack(app, 'ScheduledEventStack');

const rule = new events.Rule(stack, 'MyScheduledRule', {
  schedule: events.Schedule.rate(cdk.Duration.minutes(5))
});

rule.addTarget(new targets.LambdaFunction(myLambdaFunction));

app.synth();

Other packages similar to @aws-cdk/aws-events

Changelog

Source

1.135.0 (2021-12-10)

⚠ BREAKING CHANGES TO EXPERIMENTAL FEATURES

  • apigatewayv2-authorizers: The default value for the prop authorizerName in HttpJwtAuthorizerProps has changed.
  • apigatewayv2-authorizers: HttpJwtAuthorizer now takes the construct id and the target jwt issuer as part of its constructor.
  • apigatewayv2-authorizers: HttpLambdaAuthorizer now takes the construct id and the target lambda function handler as part of its constructor.
  • apigatewayv2-authorizers: The default value for the prop authorizerName in HttpUserPoolAuthorizerProps has changed.
  • apigatewayv2: The HttpIntegration and WebSocketIntegration classes require an "id" parameter to be provided during its initialization.
  • apigatewayv2-integrations: The LambdaWebSocketIntegration is now renamed to WebSocketLambdaIntegration. The new class accepts the handler to the target lambda function directly in its constructor.
  • apigatewayv2-integrations: HttpProxyIntegration and HttpProxyIntegrationProps are now renamed to HttpUrlIntegration and HttpUrlIntegrationProps respectively. The new class accepts the target url directly in its constructor.
  • apigatewayv2-integrations: LambdaProxyIntegration and LambdaProxyIntegrationProps are now renamed to HttpLambdaIntegration and HttpLambdaIntegrationProps respectively. The new class accepts the lambda function handler directly in its constructor.
  • apigatewayv2-integrations: HttpAlbIntegration now accepts the ELB listener directly in its constructor.
  • apigatewayv2-integrations: HttpNlbIntegration now accepts the ELB listener directly in its constructor.
  • apigatewayv2-integrations: HttpServiceDiscoveryIntegration now accepts the service discovery Service directly in its constructor.
  • apigatewayv2-authorizers: UserPoolAuthorizerProps is now renamed to HttpUserPoolAuthorizerProps.
  • apigatewayv2: The interface IHttpRouteIntegration is replaced by the abstract class HttpRouteIntegration.
  • apigatewayv2: The interface IWebSocketRouteIntegration is now replaced by the abstract class WebSocketRouteIntegration.
  • apigatewayv2: Previously, we allowed the usage of integration classes to be used with routes defined in multiple HttpApi instances (or WebSocketApi instances). This is now disallowed, and separate instances must be created for each instance of HttpApi or WebSocketApi.

Features

Bug Fixes

  • apigateway: dataTraceEnabled does not default to false (#17906) (cc3bb1f)
  • apigatewayv2: integration class does not render an integration resource (#17729) (3b5b97a), closes #13213
  • apprunner: startCommand and environment are ignored in imageConfiguration (#16939) (d911c58), closes #16812
  • appsync: add caching config to AppSync resolvers (#17815) (52b535b)
  • appsync: empty caching config is created when not provided (#17947) (3a9f206)
  • appsync: remove 'id' suffix to union definition key (#17787) (86e7780), closes #17771
  • assert: support multiline strings with stringLike() (#17692) (37596e6)
  • assets: remove the original-path metadata (#17901) (2b759ca), closes #17706
  • aws-cdk-migration: Construct imports not rewritten (#17931) (f02fcb4), closes #17826
  • aws-ec2: imported VPC subnets never recognized as PRIVATE_ISOLATED (#17496) (ba6a8ef)
  • aws-elasticloadbalancingv2: Set stickiness.enabled unless target type is lambda (#17271) (168a98f), closes #17261
  • cli: S3 asset uploads are rejected by commonly referenced encryption SCP (introduces bootstrap stack v9) (#17668) (8191f1f), closes #11265
  • codepipeline: cannot trigger on all tags anymore in EcrSourceAction (#17270) (39fe11b), closes aws#13818 aws#13818
  • codepipeline: cross-env pipeline cannot be created in Stage (#17730) (f17f29e), closes #17643
  • codepipeline: default cross-region S3 buckets allow public access (#17722) (0b80db5), closes #16411
  • cognito: remove invalid SES region check (#17868) (450f7ca), closes #17795
  • core: bundling skipped with --exclusively option and stacks under stage (#17210) (cda6601), closes #12898 #15346
  • docdb: secret rotation ignores excluded characters in password (#17609) (1fe2215), closes #17347 #17575
  • dynamodb: add missing DynamoDB operations to enum (#17738) (f38e0ac)
  • dynamodb: changing waitForReplicationToFinish fails deployment (#17842) (36b8fdb), closes #16983
  • iam: AWS Managed Policy ARNs are not deduped (#17623) (ed4a4b4), closes #17552
  • lambda-nodejs: bundling fails with a file dependency in nodeModules (#17851) (5737c33), closes #17830
  • lambda-nodejs: bundling with nodeModules fails with paths containing spaces (#17632) (986f291), closes #17631
  • pipelines: stack outputs used in stackSteps not recognized (#17311) (5e4a219), closes #17272
  • s3-deployment: updating memoryLimit or vpc results in stack update failure (#17530) (2ba40d1), closes #7128
  • stepfunctions: prefixes not appended to states in parallel branches (#17806) (a1da772), closes #17354

Miscellaneous Chores

  • apigatewayv2: integration api re-organization (#17752) (29039e8)
  • apigatewayv2-authorizers: re-organize authorizer api (#17772) (719f33e)

Readme

Source

Amazon EventBridge Construct Library


cfn-resources: Stable

cdk-constructs: Stable


Amazon EventBridge delivers a near real-time stream of system events that describe changes in AWS resources. For example, an AWS CodePipeline emits the State Change event when the pipeline changes its state.

  • Events: An event indicates a change in your AWS environment. AWS resources can generate events when their state changes. For example, Amazon EC2 generates an event when the state of an EC2 instance changes from pending to running, and Amazon EC2 Auto Scaling generates events when it launches or terminates instances. AWS CloudTrail publishes events when you make API calls. You can generate custom application-level events and publish them to EventBridge. You can also set up scheduled events that are generated on a periodic basis. For a list of services that generate events, and sample events from each service, see EventBridge Event Examples From Each Supported Service.
  • Targets: A target processes events. Targets can include Amazon EC2 instances, AWS Lambda functions, Kinesis streams, Amazon ECS tasks, Step Functions state machines, Amazon SNS topics, Amazon SQS queues, Amazon CloudWatch LogGroups, and built-in targets. A target receives events in JSON format.
  • Rules: A rule matches incoming events and routes them to targets for processing. A single rule can route to multiple targets, all of which are processed in parallel. Rules are not processed in a particular order. This enables different parts of an organization to look for and process the events that are of interest to them. A rule can customize the JSON sent to the target, by passing only certain parts or by overwriting it with a constant.
  • EventBuses: An event bus can receive events from your own custom applications or it can receive events from applications and services created by AWS SaaS partners. See Creating an Event Bus.

Rule

The Rule construct defines an EventBridge rule which monitors an event based on an event pattern and invoke event targets when the pattern is matched against a triggered event. Event targets are objects that implement the IRuleTarget interface.

Normally, you will use one of the source.onXxx(name[, target[, options]]) -> Rule methods on the event source to define an event rule associated with the specific activity. You can targets either via props, or add targets using rule.addTarget.

For example, to define an rule that triggers a CodeBuild project build when a commit is pushed to the "master" branch of a CodeCommit repository:

declare const repo: codecommit.Repository;
declare const project: codebuild.Project;

const onCommitRule = repo.onCommit('OnCommit', {
  target: new targets.CodeBuildProject(project),
  branches: ['master']
});

You can add additional targets, with optional input transformer using eventRule.addTarget(target[, input]). For example, we can add a SNS topic target which formats a human-readable message for the commit.

For example, this adds an SNS topic as a target:

declare const onCommitRule: events.Rule;
declare const topic: sns.Topic;

onCommitRule.addTarget(new targets.SnsTopic(topic, {
  message: events.RuleTargetInput.fromText(
    `A commit was pushed to the repository ${codecommit.ReferenceEvent.repositoryName} on branch ${codecommit.ReferenceEvent.referenceName}`
  )
}));

Or using an Object:

declare const onCommitRule: events.Rule;
declare const topic: sns.Topic;

onCommitRule.addTarget(new targets.SnsTopic(topic, {
  message: events.RuleTargetInput.fromObject(
    {
      DataType: `custom_${events.EventField.fromPath('$.detail-type')}`
    }
  )
}));

Scheduling

You can configure a Rule to run on a schedule (cron or rate). Rate must be specified in minutes, hours or days.

The following example runs a task every day at 4am:

import { Rule, Schedule } from '@aws-cdk/aws-events';
import { EcsTask } from '@aws-cdk/aws-events-targets';
import { Cluster, TaskDefinition } from '@aws-cdk/aws-ecs';
import { Role } from '@aws-cdk/aws-iam';

declare const cluster: Cluster;
declare const taskDefinition: TaskDefinition;
declare const role: Role;

const ecsTaskTarget = new EcsTask({ cluster, taskDefinition, role });

new Rule(this, 'ScheduleRule', {
 schedule: Schedule.cron({ minute: '0', hour: '4' }),
 targets: [ecsTaskTarget],
});

If you want to specify Fargate platform version, set platformVersion in EcsTask's props like the following example:

declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;
declare const role: iam.Role;

const platformVersion = ecs.FargatePlatformVersion.VERSION1_4;
const ecsTaskTarget = new targets.EcsTask({ cluster, taskDefinition, role, platformVersion });

Event Targets

The @aws-cdk/aws-events-targets module includes classes that implement the IRuleTarget interface for various AWS services.

The following targets are supported:

  • targets.CodeBuildProject: Start an AWS CodeBuild build
  • targets.CodePipeline: Start an AWS CodePipeline pipeline execution
  • targets.EcsTask: Start a task on an Amazon ECS cluster
  • targets.LambdaFunction: Invoke an AWS Lambda function
  • targets.SnsTopic: Publish into an SNS topic
  • targets.SqsQueue: Send a message to an Amazon SQS Queue
  • targets.SfnStateMachine: Trigger an AWS Step Functions state machine
  • targets.BatchJob: Queue an AWS Batch Job
  • targets.AwsApi: Make an AWS API call

Cross-account and cross-region targets

It's possible to have the source of the event and a target in separate AWS accounts and regions:

import { App, Stack } from '@aws-cdk/core';
import * as codebuild from '@aws-cdk/aws-codebuild';
import * as codecommit from '@aws-cdk/aws-codecommit';
import * as targets from '@aws-cdk/aws-events-targets';

const app = new App();

const account1 = '11111111111';
const account2 = '22222222222';

const stack1 = new Stack(app, 'Stack1', { env: { account: account1, region: 'us-west-1' } });
const repo = new codecommit.Repository(stack1, 'Repository', {
  repositoryName: 'myrepository',
});

const stack2 = new Stack(app, 'Stack2', { env: { account: account2, region: 'us-east-1' } });
const project = new codebuild.Project(stack2, 'Project', {
  // ...
});

repo.onCommit('OnCommit', {
  target: new targets.CodeBuildProject(project),
});

In this situation, the CDK will wire the 2 accounts together:

  • It will generate a rule in the source stack with the event bus of the target account as the target
  • It will generate a rule in the target stack, with the provided target
  • It will generate a separate stack that gives the source account permissions to publish events to the event bus of the target account in the given region, and make sure its deployed before the source stack

For more information, see the AWS documentation on cross-account events.

Archiving

It is possible to archive all or some events sent to an event bus. It is then possible to replay these events.

const bus = new events.EventBus(this, 'bus', {
  eventBusName: 'MyCustomEventBus'
});

bus.archive('MyArchive', {
  archiveName: 'MyCustomEventBusArchive',
  description: 'MyCustomerEventBus Archive',
  eventPattern: {
    account: [Stack.of(this).account],
  },
  retention: Duration.days(365),
});

Granting PutEvents to an existing EventBus

To import an existing EventBus into your CDK application, use EventBus.fromEventBusArn, EventBus.fromEventBusAttributes or EventBus.fromEventBusName factory method.

Then, you can use the grantPutEventsTo method to grant event:PutEvents to the eventBus.

declare const lambdaFunction: lambda.Function;

const eventBus = events.EventBus.fromEventBusArn(this, 'ImportedEventBus', 'arn:aws:events:us-east-1:111111111:event-bus/my-event-bus');

// now you can just call methods on the eventbus
eventBus.grantPutEventsTo(lambdaFunction);

Keywords

FAQs

Package last updated on 10 Dec 2021

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc