Home > Enterprise >  Re-use "common variables" in terraform for Lambda environment variables
Re-use "common variables" in terraform for Lambda environment variables

Time:04-27

Let's say I have multiple lambda's with their own specific env vars but also share a list of common env vars, how can I define the common env vars in one location and use "spread" that into the lambda's env var definition?

In Javascript, you could use the spread operator, so something like this

COMMON_VARS = {
  COMMON_VAR_1 = var.common_var_1
  COMMON_VAR_2 = var.common_var_2
}

resource "aws_lambda_function" "lambda_1" {
  ...
  environment {
    variables = {
      LAMBDA_VAR_1      = var.lambda_var_1
      ...COMMON_VARS
    }
  }
  ...
}

resource "aws_lambda_function" "lambda_2" {
  ...
  environment {
    variables = {
      LAMBDA_VAR_2      = var.lambda_var_2
      ...COMMON_VARS
    }
  }
  ...
}

Note that all the var.* variables will be defined in variable blocks.

CodePudding user response:

You can use merge to combine common and new variables:

resource "aws_lambda_function" "lambda_1" {
  ...
  environment {
    variables = merge(var.COMMON_VARS, {
      LAMBDA_VAR_1      = var.lambda_var_1
    })
  }
  ...
}

resource "aws_lambda_function" "lambda_2" {
  ...
  environment {
    variables = merge(var.COMMON_VARS, {
      LAMBDA_VAR_2      = var.lambda_var_2
    })
  }
  ...
}
  • Related