How do I add a lambda environmental variable with terraform?

Strawberry picture Strawberry · Oct 27, 2018 · Viewed 10.7k times · Source

I want my lambda to call APIs, and that requires an API token. I want to place the API token into a lambda environment variable. How can I have terraform do this instead? Or am I approaching this the wrong way?

Answer

Jarred Olson picture Jarred Olson · Oct 27, 2018

The Documentation here gives a pretty good example. Basically it's a environment block with a variables block. Then whatever key value pairs you want. Assuming you're using nodejs you can then refer to these variables in your lambda code by doing process.env.api_key. These values would be stored in plain text in your terraform code as well as the terraform state file. AWS encrypts the environment variables but you do need to concern yourself with how those values get there. If you are uncomfortable with them being stored in git and whatever storage you use for your state file then you can add them in manually through the console.

resource "aws_lambda_function" "test_lambda" {
  filename         = "lambda_function_payload.zip"
  function_name    = "lambda_function_name"
  runtime          = "nodejs8.10"
  ...

  environment {
    variables = {
      api_key = "super_secret"
    }
  }
}