Home > Net >  Terraform: Dynamically reference environment variables as values
Terraform: Dynamically reference environment variables as values

Time:09-13

How can I dynamically use the value of an environment variable as a value in a Terraform resource, without having to declare a corresponding Terraform variable?

For example, imagine I declare a variable that contains a list of environment variable names:

variable "env_vars" {
    description = "A list of env vars to use"
}

And I define a .tfvars file that sets the value of that list:

env_vars = ["ENV_VAR_A", "ENV_VAR_B", "ENV_VAR_C"]

Then imagine some arbitrary resource with a name argument. I want to dynamically create 1 resource for each item in the env_vars list, with the value of name set to the value of the environment variable of the same name:

resource "arbitrary_thing" "thing" {
  count = length(var.env_vars)
  name = "<VALUE OF ENV VAR NAMED var.env_vars[count.index] >"
}

How can I correctly set that name value?

CodePudding user response:

This is not a supported functionality in Terraform.

However, HashiCorp (maintainers of Terraform) have posted a support/help article on how you can achieve a workaround.

CodePudding user response:

resource "arbitrary_thing" "thing" {
  count = length(var.env_vars)
  name =var.env_vars[count.index]
}

variable "env_vars" {
    description = "A list of env vars to use"
}

And I define a .tfvars file that sets the value of that list:

env_vars = ["ENV_VAR_A", "ENV_VAR_B", "ENV_VAR_C"]
  • Related