Lambda Scheduling & Event Filtering with EventBridge using Serverless Framework
Tags: aws, serverless, eventbridge, lambda
Published: 2023-12-24 14:30:13

Lambda Scheduling & Event Filtering with EventBridge using Serverless Framework

#####Application Stack:
* Serverless Framework
* AWS EventBridge
* AWS Lambda
* NodeJs

In this post, We will take a look at a use-case that allows us to schedule lambda function call and custom event pattern matching based lambda function call with EventBridge using Serverless Framework.

#####AWS Architecture:

![AWS Architecture](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xaklsq1lucrlhjcbgcyy.png)
Above is an AWS Serverless architecture diagram showing EventBridge calling Lambda, using scheduled rules, and filtering lambda calls using custom even pattern matching rules. 

#### 1. Install Serverless Framework

```
npm install -g serverless
```

#### 2. Create basic NodeJs type template project using Serverless Framework

```
serverless create --template aws-nodejs
```

By default it will generate a folder structure like this:
* handler.js
* serverless.yml

Default serverless.yml will have below IaC code:

```
service: default-aws-nodejs
frameworkVersion: '2'
provider:
  name: aws
  runtime: nodejs12.x
  lambdaHashingVersion: 20201221

functions:
  hello:
    handler: handler.hello
```

Default handler.js will have below NodeJs code:

```
'use strict';

module.exports.hello = async (event) => {
  return {
    statusCode: 200,
    body: JSON.stringify(
      {
        message: 'Go Serverless v1.0! Your function executed successfully!',
        input: event,
      },
      null,
      2
    ),
  };
};

```

#### 3. Modify serverless.yml Infrastructure as code to provision needful Lambda functions with EventBridge as Event Source

```
service: sls-eventbridge
frameworkVersion: '2'
provider:
  name: aws
  runtime: nodejs12.x
  lambdaHashingVersion: 20201221
  stage: dev
  region: ap-south-1

functions:
  scheduledService:
    handler: handler.scheduledService
    events:
      - schedule: rate(1 minute)

  invoiceService:
    handler: handler.invoiceService
    events:
      - cloudwatchEvent:
          event:            
            detail:
              operation:
                - invoice-service

  rewardService:
    handler: handler.rewardService
    events:
      - cloudwatchEvent:
          event:            
            detail:
              operation:
                - reward-service
```

#### 4. Modify handler.js with below sample demo code

```
'use strict';

const scheduledService = async (event) => {
  console.log(event);
  return {
    statusCode: 200,
    body: JSON.stringify(
      {
        message: 'scheduledService lambda function call through EventBridge scheduling rule!',
        input: event,
      },
      null,
      2
    ),
  };
};

const invoiceService = async (event) => {
  console.log(event);
  return {
    statusCode: 200,
    body: JSON.stringify(
      {
        message: 'invoiceService lambda function call through EventBridge custom pattern matching!',
        input: event,
      },
      null,
      2
    ),
  };
};

const rewardService = async (event) => {
  console.log(event);
  return {
    statusCode: 200,
    body: JSON.stringify(
      {
        message: 'rewardService lambda function call through EventBridge custom pattern matching!',
        input: event,
      },
      null,
      2
    ),
  };
};

module.exports = {
  scheduledService,
  invoiceService,
  rewardService
};
```

#### 5. Create AWS IAM user with programmatic access and give needful permission that allows Serverless Framework to provision resources

The Serverless Framework needs access to your cloud provider account so that it can create and manage resources on your behalf.

During Creating AWS IAM user copy API Key & Secret.

#### 6. Configure AWS Credentials for Serverless Framework Deployment

```
serverless config credentials --provider aws --key xxxxx --secret xxxxx
```

#### 7. Deploy using Serverless Framework

```
serverless deploy
```

```
> serverless deploy
Serverless: Packaging service...
Serverless: Excluding development dependencies...
Serverless: Service files not changed. Skipping deployment...
Service Information
service: sls-eventbridge
stage: dev
region: ap-south-1
stack: sls-eventbridge-dev
resources: 18
api keys:
  None
endpoints:
  None
functions:
  scheduledService: sls-eventbridge-dev-scheduledService
  invoiceService: sls-eventbridge-dev-invoiceService
  rewardService: sls-eventbridge-dev-rewardService
layers:
  None
```

#### 8. Amazon EventBridge and AWS Lambda Screenshots
##### AWS Lambda Functions List
![AWS Lambda Functions List](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hwuf1of1oz3cd5yrdnew.png)

##### AWS Lambda Functions Event Source Configuration
![AWS Lambda Functions List](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mc469nux80zwu58o4swt.png)

##### Amazon EventBridge Default Bus Scheduling Rules
![Amazon EventBridge Default Bus Rules](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1ef3auho1o8d9x7742qp.png)

##### Amazon EventBridge Default Bus Custom Event Pattern Rule
![Amazon EventBridge Default Bus Custom Event Pattern Rule](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2no92yd5ey1j49sbpy7p.png)

##### Amazon EventBridge Default Bus Custom Event Pattern Rule
![Amazon EventBridge Default Bus Custom Event Pattern Rule](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ad3gtwsusejpwif1nmzj.png)

#### 9. Remove already provisioned resources

```
serverless remove
```

#### Relevant Resources Link
* Serverless Framework: https://www.serverless.com/
* AWS EventBridge: https://aws.amazon.com/eventbridge/
* AWS Lambda: https://aws.amazon.com/lambda/
* NodeJs: https://nodejs.org/