How to Run AWS lambda as cron in AWS - IaC with terraform

If you are an AWS user, you probably know that AWS Lambda is a great way to run code on the cloud. Sometimes you might have scripts that you want to run on a schedule, and AWS Lambda is the perfect tool for that.

In this post, I will show you how to run AWS Lambda functions as cron jobs.

The lambda function

I have a simple javascript lambda that alerts me when no user signed up in the past hour. It is meant to run hourly. The function connects to a mongodb database named citizix, then runs a mongo query to count records created in the past hour in the users schema.

I then check if no records exist I use a make hook to send slack alert.

Create the project dir

1
2
3
mkdir user-checks

cd user-checks

Initialize empty node project

1
npm init -y

Install mongodb package

1
npm install mongodb

Create an index.js file

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
const { MongoClient } = require("mongodb");

const uri = process.env.MONGODB_URI;
const dbName = "citizix";
const collectionName = "users";

exports.handler = async (event) => {
  const client = new MongoClient(uri);

  try {
    await client.connect();

    const database = client.db(dbName);
    const collection = database.collection(collectionName);

    const oneHourAgo = new Date(Date.now() - 1000 * 60 * 60);
    const query = { createdAt: { $gt: oneHourAgo } };

    const count = await collection.countDocuments(query);

    if (count === 0) {
      const payload = {
        type: "user-signups-check",
        data: {
          message: "Alert: No users signed up in the past hour.",
        },
      };

      await fetch(
        "https://hook.us1.make.com/mnmgna98a0xd61ys48kaqke37h5m575u",
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(payload),
        }
      );
    } else {
      console.log(`Found ${count} user signups in the past hour.`);
    }
  } catch (error) {
    console.error("Error checking user signups:", error);
    throw new Error("Error checking signups");
  } finally {
    await client.close();
  }
};

Creating AWS Lambda using terraform

Create a terraform directory

1
mkdir tf

Then we need to zip our index file and node dependencies into terraform dir so we can use it to create our lambda function.

1
zip -r tf/code.zip index.js node_modules

We can also create our env variable as a secret so we don’t expose

1
2
3
4
5
6
aws secretsmanager create-secret \
    --region=us-west-2 \
        --secret-id production-mongodb \
        --secret-string '{
  "MONGO_URI": "mongodb+srv://user:secretP4ss@mongo-host.url"
}'

We can then create a terraform code to create our terragrunt

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
provider "aws" {
  region = "us-west-2"
}

resource "aws_iam_role_policy" "policy" {
  name   = "lambda_vpc_policy"
  role   = aws_iam_role.role.id

  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Effect = "Allow"
        Action = [
          "ec2:CreateNetworkInterface",
          "ec2:DescribeNetworkInterfaces",
          "ec2:DeleteNetworkInterface",
          "ec2:DescribeSubnets",
          "ec2:AssignPrivateIpAddresses",
          "ec2:UnassignPrivateIpAddresses"
        ]
        Resource = "*"
      }
    ]
  })
}

resource "aws_iam_role" "role" {
  name = "checkUserSignup"

  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Action = "sts:AssumeRole"
        Principal = {
          Service = "lambda.amazonaws.com"
        }
        Effect = "Allow"
        Sid    = ""
      },
    ]
  })
}

resource "aws_iam_policy_attachment" "attachment" {
  name       = "checkUserSignupAttachment"
  roles      = [aws_iam_role.role.name]
  policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
}

data "aws_secretsmanager_secret" "production_mongodb" {
  name = "production-mongodb"
}

data "aws_secretsmanager_secret_version" "production_mongodb_version" {
  secret_id = data.aws_secretsmanager_secret.production_mongodb.id
}

locals {
  secret_value = jsondecode(data.aws_secretsmanager_secret_version.production_mongodb_version.secret_string)
}

resource "aws_lambda_function" "function" {
  function_name = "checkUserSignups"
  role          = aws_iam_role.role.arn
  handler       = "index.handler"
  runtime       = "nodejs18.x"
  timeout       = 60

  filename         = "code.zip"
  source_code_hash = filebase64sha256("code.zip")

  vpc_config {
    subnet_ids         = ["subnet-xxxxx", "subnet-xxxx"]
    security_group_ids = ["sg-xxxx"]
  }

  environment {
    variables = {
      MONGODB_URI = local.secret_value["MONGO_URI"]
    }
  }
}

Next we run the lambda periodically. We do this using cloudwatch event rule

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
resource "aws_cloudwatch_event_rule" "every_hour" {
  name                = "checkUserSignupHourlyCheck"
  schedule_expression = "cron(0 * * * ? *)"
}

resource "aws_cloudwatch_event_target" "lambda_target" {
  rule      = aws_cloudwatch_event_rule.every_hour.name
  target_id = "checkUserSignup"
  arn       = aws_lambda_function.function.arn
}

resource "aws_lambda_permission" "allow_cloudwatch" {
  statement_id  = "AllowCheckUserSignupExecutionFromCloudWatch"
  action        = "lambda:InvokeFunction"
  function_name = aws_lambda_function.function.function_name
  principal     = "events.amazonaws.com"
  source_arn    = aws_cloudwatch_event_rule.every_hour.arn
}

Creating AWS resources

One you have the code in place

1
terraform plan

Apply

1
terraform apply
comments powered by Disqus
Citizix Ltd
Built with Hugo
Theme Stack designed by Jimmy