Search code examples
serverless-framework

How can I set up 2 AWS lambda functions, with one firing an event on eventBridge and the other reacting to it?


I'm using the serverless framework to try and test EventBridge.

The documentation is a little sparce, but for my test I would like to have two lambda functions created: first one publishes an event, the second consumes it.

Here is my YAML:

service: events
frameworkVersion: '2'

provider:
  name: aws
  runtime: nodejs12.x
  lambdaHashingVersion: '20201221'

functions:
  vehicle:
    handler: handler.vehicle
    events:
      - httpApi:
          path: /vehicle
          method: '*'
  bundle:
    handler: handler.bundle
    events:
      - httpApi:
          path: /bundle
          method: '*'
      - eventBridge:
          eventBus: vehicle-bus 
          pattern:
            source:
              - aos.vehicle.upload
          detail-type:
            - VehicleUpload

and my handler.js

"use strict";
const AWS = require('aws-sdk');

module.exports.vehicle = async (event) => {
  const eventBridge = new AWS.EventBridge({ region: 'us-east-1' });

  const vrm = 'WR17MMN'
  return eventBridge.putEvents({
    Entries: [
      {
        EventBusName: 'veihcle-bus',
        Source: 'aos.vehicle.upload',
        DetailType: 'VehicleUpload',
        Detail: `{ "Registration": "${vrm}" }`,
      },
    ]
  }).promise()
};

module.exports.bundle = async (event) => {
  return {
    statusCode: 200,
    body: JSON.stringify(
      {
        message: "BUNDLE",
        input: event,
        aos: "First test OK",
      },
      null,
      2
    ),
  };
};

(I realise I can't just return that from the Lambda but it also needs to be an endpoint. If I make the function body of bundle empty I still get a server error.

What am I missing?


Solution

  • So you need this minimal setup:

    org: myOrg
    app: my-events
    service: event-bridge-serverless
    
    provider:
      name: aws
      runtime: nodejs10.x
      region: eu-west-1
      lambdaHashingVersion: 20201221
      environment:
        DYNAMODB_TABLE: ${self:service}-dev
      eventBridge:
        useCloudFormation: true
    
    iamRoleStatements:
      - Effect: "Allow"
        Action:
            - "events:PutEvents"
        Resource: "*"
    
    
    functions:
      asset:
         handler: handler.asset
        events:
          - eventBridge:
            eventBus: my-events 
            pattern:
               source:
                 - my.event