Sling Academy
Home/DevOps/Terraform: How to trigger a Lambda function on resource creation

Terraform: How to trigger a Lambda function on resource creation

Last updated: February 04, 2024

Overview

Integrating AWS Lambda with Terraform can lead to efficient and scalable cloud infrastructure, managing resources and executing serverless operations effectively. This tutorial dives into the specifics of triggering an AWS Lambda function upon the creation of a resource using Terraform, allowing for automated workflows and operations in response to changes in your infrastructure.

Prerequisites

  • AWS Account: An active AWS account is required.
  • Terraform Installed: Ensure Terraform is installed and configured on your machine.
  • Basic Knowledge: Familiarity with AWS Lambda and Terraform is helpful.

Step 1: Setting up AWS Lambda

Let’s start by setting up the AWS Lambda function that you want to trigger.

resource "aws_lambda_function" "example" {
  function_name = "exampleFunction"
  filename         = "path/to/your/lambda/deployment/package.zip"
  source_code_hash = filebase64sha256("path/to/your/lambda/deployment/package.zip")
  handler          = "index.handler"
  runtime          = "nodejs12.x"
  role             = aws_iam_role.lambda_exec.arn
}

Create an IAM role with the necessary permissions for your Lambda function to execute. Here’s an example:

resource "aws_iam_role" "lambda_exec" {
  name = "lambda_execution_role"
  assume_role_policy = <

Step 2: Configuring the Trigger with Terraform

To configure Terraform to trigger the Lambda function upon a specific event, such as the creation of a new AWS resource, you utilize the aws_lambda_permission resource and a Custom Resource implemented through AWS CloudFormation, initiated by Terraform.

This permits the Lambda function to be invoked by an AWS service or resource directly. For example, to have Lambda be triggered on creation of an S3 bucket:

resource "aws_lambda_permission" "example_lambda_permission" {
  statement_id  = "AllowExecutionFromS3"
  action        = "lambda:InvokeFunction"
  function_name = aws_lambda_function.example.function_name
  principal     = "s3.amazonaws.com"
  source_arn    = "arn:aws:s3:::${aws_s3_bucket.example.bucket}"
}

Next, define a custom resource that will act as the trigger:

resource "aws_cloudformation_stack" "s3_notification" {
  name = "S3NotificationToLambda"
  template_body = <<TEMPLATE
{
  "Resources": {
    "CustomResource": {
      "Type": "Custom::TestResource",
      "Properties": {
        "ServiceToken": aws_lambda_function.example.arn,
      }
    }
  }
}
TEMPLATE
}

Step 3: Terraform Apply

With configurations set, apply your Terraform plan to provision the resources and set up the trigger:

terraform apply

This command creates the specified AWS Lambda function and configures it to be triggered under the defined condition. Make sure you review the proposed changes before applying them.

Testing Your Setup

Once everything is deployed, you can test the trigger by creating the source resource (e.g., an S3 bucket). If the setup is correct, creating the bucket should automatically call the Lambda function.

Remember, this tutorial only covers a specific scenario. AWS Lambda and Terraform can interact in many ways, depending on your requirements. Experiment with different resources and triggers to best meet your needs.

Conclusion

Integrating Terraform and AWS Lambda enables powerful, automated serverless architectures. Using Terraform to trigger Lambda functions adds a layer of dynamism to your cloud infrastructure, allowing for automatic execution of functions in response to events. With the steps outlined in this tutorial, you’re well on your way to leveraging this capability in your AWS environment.

Exploring further will reveal even greater potentials for automation and efficiency in your cloud operations. Happy codings!

Next Article: Terraform Error – MalformedPolicyDocument: Has prohibited field Resource

Previous Article: Terraform Error: The provider ‘aws’ does not support resource type ‘aws_instance’

Series: Terraform Tutorials

DevOps

You May Also Like

  • How to reset Ubuntu to factory settings (4 approaches)
  • Making GET requests with cURL: A practical guide (with examples)
  • Git: What is .DS_Store and should you ignore it?
  • NGINX underscores_in_headers: Explained with examples
  • How to use Jenkins CI with private GitHub repositories
  • Terraform: Understanding State and State Files (with Examples)
  • SHA1, SHA256, and SHA512 in Terraform: A Practical Guide
  • CSRF Protection in Jenkins: An In-depth Guide (with examples)
  • Terraform: How to Merge 2 Maps
  • Terraform: How to extract filename/extension from a path
  • JSON encoding/decoding in Terraform: Explained with examples
  • Sorting Lists in Terraform: A Practical Guide
  • How to use Terraform templates
  • Understanding terraform_remote_state data source: Explained with examples
  • Jenkins Authorization: A Practical Guide (with examples)
  • Solving Jenkins Pipeline NotSerializableException: groovy.json.internal.LazyMap
  • Understanding Artifacts in Jenkins: A Practical Guide (with examples)
  • Using Jenkins with AWS EC2 and S3: A Practical Guide
  • Terraform: 3 Ways to Remove Duplicates from a List