How can I enable deployment of individual Lambda functions using Terraform?

Viewed 213

I'm working on automating deployment of Lambda functions using Terraform. The goal is to be able to deploy either a single Lambda function or all of the functions in the repo. I'm able to deploy a number of functions from a structure that looks like:

├── README.md
├── js
│   ├── README.md
│   ├── jsFunction1/
│   │   └── main.tf
│   └── jsFunction2/
│       └── main.tf
├── py
│   ├── README.md
│   ├── pyFunction1/
│   │   └── main.tf
│   └── pyFunction2/
│       └── main.tf
└── terraform
    ├── README.md
    ├── common/
    ├── global/
    ├── main.tf
    ├── modules/
    ├── prod/
    └── stage/

The goal is to be able to deploy js/jsFunction1 independently (without building packages for any other functions) while also having terraform/main.tf able to deploy all the lambda functions in the repository (after they've been built). This is so a developer can update the stage deployment with changes to an individual function without concern that they might have an improper version of a function that the developer isn't working on.

What I was hoping to do is create a back-end for each Lambda function so that the developer can use terraform apply from within the source folder. I don't see how to import the state of the Lambda functions that were deployed from the terraform/ module. Can you tell me if importing the state of the resources is a reasonable approach or recommend a better way to achieve the ability to deploy one of many Lambda functions?

Here is the main.tf from js/jsFunction1

module "jsFunction1" {
  source                        = "../../terraform/modules/lambda"
  source_path                   = "${path.module}/dist"
  lambda_function_name          = "jsFunction1"
  lambda_handler                = "lambdaAdapter.handler"
}

There is a similar main.tf in each of the folders under js and py. This is main.tf from the terraform folder

module "jsFunction1" {
    source = "./../js/jsFunction1"
}

module "jsFunction2" {
    source = "./../js/jsFunction2"
}

module "pyFunction1" {
    source = "./../py/pyFunction1"
}

module "pyFunction2" {
    source = "./../py/pyFunction2"
}
1 Answers

You can make use lambda package module to zip seperate packages for specific lambda's and deploy them.

The package module has the ability to build the package only if change is happened in the respective folders.

So you can have a single main.tf and the reference the output values from package module.

Related