Security News
JSR Working Group Kicks Off with Ambitious Roadmap and Plans for Open Governance
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
@aws-cdk/aws-events
Advanced tools
@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.
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();
The aws-sdk package is the official AWS SDK for JavaScript, which provides a comprehensive set of tools for interacting with AWS services, including EventBridge. Unlike @aws-cdk/aws-events, which is used for defining infrastructure as code, aws-sdk is used for making API calls to AWS services.
The serverless framework is a popular open-source framework for building and deploying serverless applications. It supports AWS Lambda and EventBridge, among other services. While @aws-cdk/aws-events focuses on infrastructure as code, serverless provides a higher-level abstraction for deploying serverless applications.
Pulumi is an infrastructure as code tool that supports multiple cloud providers, including AWS. It allows you to define and manage cloud resources using familiar programming languages. Pulumi can be used to manage EventBridge resources similarly to @aws-cdk/aws-events, but it offers a different approach and supports multiple clouds.
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.
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')}`
}
)
}));
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 });
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 buildtargets.CodePipeline
: Start an AWS CodePipeline pipeline executiontargets.EcsTask
: Start a task on an Amazon ECS clustertargets.LambdaFunction
: Invoke an AWS Lambda functiontargets.SnsTopic
: Publish into an SNS topictargets.SqsQueue
: Send a message to an Amazon SQS Queuetargets.SfnStateMachine
: Trigger an AWS Step Functions state machinetargets.BatchJob
: Queue an AWS Batch Jobtargets.AwsApi
: Make an AWS API callIt'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:
For more information, see the AWS documentation on cross-account events.
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),
});
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);
1.133.0 (2021-11-19)
DynamoAttributeValue.listFromJsonPath
(#17376) (bc10e6f), closes #17375Function.addEventSource
fails for ManagedKafkaEventSource
typed parameters (#17490) (a474ee8)policy.ts
exports in index.ts
exports (#17403) (a391468)FAQs
Amazon EventBridge Construct Library
The npm package @aws-cdk/aws-events receives a total of 112,074 weekly downloads. As such, @aws-cdk/aws-events popularity was classified as popular.
We found that @aws-cdk/aws-events demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 4 open source maintainers collaborating on the project.
Did you know?
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.
Security News
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
Security News
Research
An advanced npm supply chain attack is leveraging Ethereum smart contracts for decentralized, persistent malware control, evading traditional defenses.
Security News
Research
Attackers are impersonating Sindre Sorhus on npm with a fake 'chalk-node' package containing a malicious backdoor to compromise developers' projects.