crunchcrunch

crunchcrunch

Schedule AWS Lambda Function with CDK

In this tutorial, i'm gonna show you how to schedule a lambda using CloudWatch Events with CDK

Make a new project

Let's create the main folder of the project

mkdir triggerLambda
cd triggerLambda
npm init -y

Then install CDK and aws-lambda package

npm install -g aws-cdk
npm i @aws-cdk/aws-lambda
npm i @aws-cdk/aws-events-targets
mkdir cdk-folder
cdk init app --language typescript

CDK part

Open the file lib/cdk-folder-stack.ts


import * as cdk from '@aws-cdk/core';
import * as lambda from '@aws-cdk/aws-lambda';
import * as path from 'path';
import * as events from "@aws-cdk/aws-events";
import * as targets from "@aws-cdk/aws-events-targets";

export class CdkFolderStack extends cdk.Stack {
  constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    // The code that defines the lambda

    const myLambdaFunction = new lambda.Function(this, 'my-lambda', {
      runtime: lambda.Runtime.NODEJS_14_X,
      memorySize: 256,
      timeout: cdk.Duration.seconds(60),
      handler: 'index.main',
      code: lambda.Code.fromAsset(path.join(__dirname, '/../app')),
    });

   // The code that defines the cron 
   const myCronJob = new events.Rule(this, "myCronJob", {
      ruleName: "myCronJob",
      description: "Trigger the lambda",
      schedule: events.Schedule.expression("cron(0 12 * * ? *)"),
    });
   myCronJob.addTarget(
      new targets.LambdaFunction(myLambdaFunction)
    );
  }
}

Create the lambda

We are going to create a folder for the lambda at the root (next to lib) :

Let's create our lambda

mkdir app/my-lambda
cd app/my-lambda
npm init -y 
npm i axios
touch index.js

Here is the code for the lambda using axios to fetch an url on internet.

const axios = require('axios');

export async function main(event) {
  try {
    const res = await axios.get('http://worldclockapi.com/api/jsonp/cet/now?callback=data')

    console.log("Lambda has been triggered at : ", res.data)
  } catch (error) {
    console.log(error)
  }
}

Let's try it

Let's bootstrap first

cdk bootstrap
⏳  Bootstrapping environment aws://XXXXXXXXXXXXX/us-east-1...
 ✅  Environment aws://XXXXXXXXXXXXXX/us-east-1 bootstrapped (no changes).

Second command, to create the Cloudformation template for our app :

cdk synth

And now, let's deploy !

cdk deploy

Go to the console

On the console, go to Lambda > your lambda

Capture d’écran 2021-09-11 à 13.51.19.png

You can see that the trigger is a Cloudwatch Event

Go to the monitoring then

Capture d’écran 2021-09-11 à 13.52.17.png

Click on "View Logs in Cloudwatch"

At the time that you decided to trigger it, you should see your logs !

Capture d’écran 2021-09-11 à 14.00.42.png

Congrats !

Now you know how to trigger a lambda with a Cloudwatch Event

Cleaning

Don't forget to clean after this tutorial, i don't want you to have a huge bill on AWS!

cdk destroy

To go further and understand Schedule Expressions : AWS documentation about Schedule Expressions for Rules

Interested in reading more such articles from Sonia Manoubi?

Support the author by donating an amount of your choice.

 
Share this