Skip to content
Permalink
Browse files

Add EventBridge event source

  • Loading branch information...
pmuens committed Jul 12, 2019
1 parent a768e2f commit 871b04e238b19bc9c57a9b430685ad157b52b98b
@@ -2,7 +2,7 @@
*.log
npm-debug.log
npm-shrinkwrap.json
/package-lock.json
package-lock.json

# Runtime data
pids
@@ -95,6 +95,7 @@ layout: Doc
<li><a href="./events/iot.md">IoT</a></li>
<li><a href="./events/cloudwatch-event.md">CloudWatch Event</a></li>
<li><a href="./events/cloudwatch-log.md">CloudWatch Log</a></li>
<li><a href="./events/event-bridge.md">EventBridge</a></li>
<li><a href="./events/cognito-user-pool.md">Cognito User Pool</a></li>
</ul>
</div>
@@ -1,7 +1,7 @@
<!--
title: Serverless Framework - AWS Lambda Events - Cognito User Pool
menuText: Cognito User Pool
menuOrder: 14
menuOrder: 15
description: Setting up AWS Cognito User Pool Triggers with AWS Lambda via the Serverless Framework
layout: Doc
-->
@@ -0,0 +1,132 @@
<!--
title: Serverless Framework - AWS Lambda Events - Event Bridge
menuText: EventBridge Event
menuOrder: 14
description: Setting up AWS EventBridge Events with AWS Lambda via the Serverless Framework
layout: Doc
-->

<!-- DOCS-SITE-LINK:START automatically generated -->

### [Read this on the main serverless docs site](https://www.serverless.com/framework/docs/providers/aws/events/event-bridge)

<!-- DOCS-SITE-LINK:END -->

# EventBridge Event

The [EventBridge](https://aws.amazon.com/eventbridge/) makes it possible to connect applications using data from external sources (e.g. own applications, SaaS) or AWS services. The `eventBridge` event types helps setting up AWS Lambda functions to react to events coming in via the EventBridge.

## Setting up a scheduled event

```yml
functions:
myFunction:
handler: index.handler
events:
- eventBridge:
schedule: rate(10 minutes)
input:
key1: value1
```

## Setting up event pattern matching

```yml
functions:
myFunction:
handler: index.handler
events:
- eventBridge:
pattern:
source:
- aws.cloudformation
detail-type:
- AWS API Call via CloudTrail
detail:
eventSource:
- cloudformation.amazonaws.com
```

## Using a different Event Bus

The `eventBridge` event source will use the `default` event bus (the one AWS uses internally) when none is explicitly specified.

The Serverless Framework will create the `eventBus` for you if you just provide a name for it. It will re-use an existing event bus if you provide an event bus `arn`.

**NOTE:** The Serverless Framework won't manage (e.g. create or remove) the event bus if it's provided via an `arn`.

### Creating an event bus

```yml
functions:
myFunction:
handler: index.handler
events:
- eventBridge:
eventBus: custom-saas-events
pattern:
source:
- saas.external
```

### Re-using an existing event bus

```yml
- eventBridge:
eventBus: arn:aws:events:us-east-1:12345:event-bus/custom-private-events
pattern:
source:
- custom.private
inputTransformer:
inputPathsMap:
eventTime: '$.time'
inputTemplate: '{"time": <eventTime>, "key1": "value1"}'
```

## Using different input types

You can specify different input types which will produce different input values ​​for the Lambda function.

```yml
functions:
myFunction:
handler: index.handler
events:
- eventBridge:
pattern:
source:
- 'aws.ec2'
detail-type:
- 'EC2 Instance State-change Notification'
detail:
state:
- pending
input:
key1: value1
key2: value2
stageParams:
stage: dev
- eventBridge:
pattern:
source:
- 'aws.ec2'
detail-type:
- 'EC2 Instance State-change Notification'
detail:
state:
- pending
inputPath: '$.stageVariables'
- eventBridge:
pattern:
source:
- 'aws.ec2'
detail-type:
- 'EC2 Instance State-change Notification'
detail:
state:
- pending
inputTransformer:
inputPathsMap:
eventTime: '$.time'
inputTemplate: '{"time": <eventTime>, "key1": "value1"}'
```
@@ -46,6 +46,7 @@
"./aws/package/compile/events/cloudWatchEvent/index.js",
"./aws/package/compile/events/cloudWatchLog/index.js",
"./aws/package/compile/events/cognitoUserPool/index.js",
"./aws/package/compile/events/eventBridge/index.js",
"./aws/package/compile/events/sqs/index.js",
"./aws/deployFunction/index.js",
"./aws/deployList/index.js",
@@ -1,9 +1,21 @@
'use strict';

const path = require('path');
const BbPromise = require('bluebird');
const _ = require('lodash');
const fse = BbPromise.promisifyAll(require('fs-extra'));
const childProcess = BbPromise.promisifyAll(require('child_process'));
const getTmpDirPath = require('../../../utils/fs/getTmpDirPath');
const createZipFile = require('../../../utils/fs/createZipFile');

function copyCustomResources(srcDirPath, destDirPath) {
return fse.ensureDirAsync(destDirPath).then(() => fse.copyAsync(srcDirPath, destDirPath));
}

function installDependencies(dirPath) {
return childProcess.execAsync(`npm install --prefix ${dirPath}`, { stdio: 'ignore' });
}

function addCustomResourceToService(resourceName, iamRoleStatements) {
let FunctionName;
let Handler;
@@ -17,107 +29,114 @@ function addCustomResourceToService(resourceName, iamRoleStatements) {
'.serverless',
this.provider.naming.getCustomResourcesArtifactDirectoryName()
);
const tmpDirPath = path.join(getTmpDirPath(), 'resources');
const funcPrefix = `${this.serverless.service.service}-${this.options.stage}`;
const zipFilePath = `${destDirPath}.zip`;
this.serverless.utils.writeFileDir(zipFilePath);

// check which custom resource should be used
if (resourceName === 's3') {
FunctionName = `${this.serverless.service.service}-${
this.options.stage
}-${this.provider.naming.getCustomResourceS3HandlerFunctionName()}`;
FunctionName = `${funcPrefix}-${this.provider.naming.getCustomResourceS3HandlerFunctionName()}`;
Handler = 's3/handler.handler';
customResourceFunctionLogicalId = this.provider.naming.getCustomResourceS3HandlerFunctionLogicalId();
} else if (resourceName === 'cognitoUserPool') {
FunctionName = `${this.serverless.service.service}-${
this.options.stage
}-${this.provider.naming.getCustomResourceCognitoUserPoolHandlerFunctionName()}`;
FunctionName = `${funcPrefix}-${this.provider.naming.getCustomResourceCognitoUserPoolHandlerFunctionName()}`;
Handler = 'cognitoUserPool/handler.handler';
customResourceFunctionLogicalId = this.provider.naming.getCustomResourceCognitoUserPoolHandlerFunctionLogicalId();
} else if (resourceName === 'eventBridge') {
FunctionName = `${funcPrefix}-${this.provider.naming.getCustomResourceEventBridgeHandlerFunctionName()}`;
Handler = 'eventBridge/handler.handler';
customResourceFunctionLogicalId = this.provider.naming.getCustomResourceEventBridgeHandlerFunctionLogicalId();
} else {
throw new Error(`No implementation found for Custom Resource "${resourceName}"`);
return BbPromise.reject(`No implementation found for Custom Resource "${resourceName}"`);
}

return createZipFile(srcDirPath, zipFilePath).then(outputFilePath => {
let S3Bucket = {
Ref: this.provider.naming.getDeploymentBucketLogicalId(),
};
if (this.serverless.service.package.deploymentBucket) {
S3Bucket = this.serverless.service.package.deploymentBucket;
}
const s3Folder = this.serverless.service.package.artifactDirectoryName;
const s3FileName = outputFilePath.split(path.sep).pop();
const S3Key = `${s3Folder}/${s3FileName}`;
// TODO: check every once in a while if external packages are still necessary
this.serverless.cli.log('Installing dependencies for custom CloudFormation resources...');
return copyCustomResources(srcDirPath, tmpDirPath)
.then(() => installDependencies(tmpDirPath))
.then(() => createZipFile(tmpDirPath, zipFilePath))
.then(outputFilePath => {
let S3Bucket = {
Ref: this.provider.naming.getDeploymentBucketLogicalId(),
};
if (this.serverless.service.package.deploymentBucket) {
S3Bucket = this.serverless.service.package.deploymentBucket;
}
const s3Folder = this.serverless.service.package.artifactDirectoryName;
const s3FileName = outputFilePath.split(path.sep).pop();
const S3Key = `${s3Folder}/${s3FileName}`;

let customResourceRole = Resources[customResourcesRoleLogicalId];
if (!customResourceRole) {
customResourceRole = {
Type: 'AWS::IAM::Role',
Properties: {
AssumeRolePolicyDocument: {
Version: '2012-10-17',
Statement: [
let customResourceRole = Resources[customResourcesRoleLogicalId];
if (!customResourceRole) {
customResourceRole = {
Type: 'AWS::IAM::Role',
Properties: {
AssumeRolePolicyDocument: {
Version: '2012-10-17',
Statement: [
{
Effect: 'Allow',
Principal: {
Service: ['lambda.amazonaws.com'],
},
Action: ['sts:AssumeRole'],
},
],
},
Policies: [
{
Effect: 'Allow',
Principal: {
Service: ['lambda.amazonaws.com'],
PolicyName: {
'Fn::Join': [
'-',
[
this.provider.getStage(),
this.provider.serverless.service.service,
'custom-resources-lambda',
],
],
},
PolicyDocument: {
Version: '2012-10-17',
Statement: iamRoleStatements,
},
Action: ['sts:AssumeRole'],
},
],
},
Policies: [
{
PolicyName: {
'Fn::Join': [
'-',
[
this.provider.getStage(),
this.provider.serverless.service.service,
'custom-resources-lambda',
],
],
},
PolicyDocument: {
Version: '2012-10-17',
Statement: iamRoleStatements,
},
},
],
},
};
} else {
const { Statement } = customResourceRole.Properties.Policies[0].PolicyDocument;
iamRoleStatements.forEach(newStmt => {
if (!Statement.find(existingStmt => existingStmt.Resource === newStmt.Resource)) {
Statement.push(newStmt);
}
});
}
};
} else {
const { Statement } = customResourceRole.Properties.Policies[0].PolicyDocument;
iamRoleStatements.forEach(newStmt => {
if (!Statement.find(existingStmt => existingStmt.Resource === newStmt.Resource)) {
Statement.push(newStmt);
}
});
}

const customResourceFunction = {
Type: 'AWS::Lambda::Function',
Properties: {
Code: {
S3Bucket,
S3Key,
},
FunctionName,
Handler,
MemorySize: 1024,
Role: {
'Fn::GetAtt': [customResourcesRoleLogicalId, 'Arn'],
const customResourceFunction = {
Type: 'AWS::Lambda::Function',
Properties: {
Code: {
S3Bucket,
S3Key,
},
FunctionName,
Handler,
MemorySize: 1024,
Role: {
'Fn::GetAtt': [customResourcesRoleLogicalId, 'Arn'],
},
Runtime: 'nodejs10.x',
Timeout: 6,
},
Runtime: 'nodejs10.x',
Timeout: 6,
},
DependsOn: [customResourcesRoleLogicalId],
};
DependsOn: [customResourcesRoleLogicalId],
};

_.merge(Resources, {
[customResourceFunctionLogicalId]: customResourceFunction,
[customResourcesRoleLogicalId]: customResourceRole,
_.merge(Resources, {
[customResourceFunctionLogicalId]: customResourceFunction,
[customResourcesRoleLogicalId]: customResourceRole,
});
});
});
}

module.exports = {

0 comments on commit 871b04e

Please sign in to comment.
You can’t perform that action at this time.