Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Re-use "common variables" in terraform for Lambda environment variables

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
    })
  }
  ...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading