6

I have two lambdas in my terraform configuration and I want them to have the exact same environment variables.

I'd like to not need to modify both lambda environment blocks every time I modify one. Is it possible to have some kind of a reusable block?

So instead of this:

resource "aws_lambda_function" "f1" {
   <..>
   environment {
    variables = {
      ENV_STAGE = "${lower(var.environment)}" # all of these will always be same for both lambdas
      A = "A"
    }
  }
}

resource "aws_lambda_function" "f2" {
  <..>
  environment {
    variables = {
      ENV_STAGE = "${lower(var.environment)}"
      A = "A"
    }
  }
}

It would be something like this:

env = {
    variables = {
      ENV_STAGE = "${lower(var.environment)}"
      A = "A"
    }
 }

resource "aws_lambda_function" "f1" {
  <..>
  environment = env
}

resource "aws_lambda_function" "f2" {
  <..>
  environment = env
}
1
  • You could combine the two resources and iterate over them twice. Whether that is feasible or not depends upon the differences between the two lambda resources. Commented Apr 15, 2020 at 14:28

2 Answers 2

4

You need a locals block

locals {
  shared_env_variables = {
    ENV_STAGE = "${lower(var.environment)}"
    A = "A"
  }
}

resource "aws_lambda_function" "f1" {
  environment {
    variables = merge(local.shared_env_variables, {
       ONLY_FOR_F1: "something"
    })
  }
}

resource "aws_lambda_function" "f2" {
  environment {
    variables = local.shared_env_variables
  }
}

More advanced things like creating resources based on a map are possible with for_each

Sign up to request clarification or add additional context in comments.

Comments

2

@dtech answer is correct, I just want to add that the syntax for v0.11 is slightly different (what I'm currently using).

Source

locals {
  common_env = {
    ENV_STAGE              = "${lower(var.environment)}"
  }
}

resource "aws_lambda_function" "Lambda" {
  <..>
  environment {
    variables = "${merge(local.common_env)}"
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.