Search code examples
terraformdevopsterraform0.12+infrastructure-as-code

Dynamic variable creation using terraform


I have this question hopefully someone will be able to shed some light on it. We have this setup in which an environment variable name is set for us with a specific prefix, and I'd like to get this value given a user input using terraform. The thing is, I would need to construct what would be the variable name given a variable value. Let me show you an example:

# let us imagine this is an environment variable set in a terraform workspace.
variable "earth_datacenter" {
  type = string
  default = "earth credentials"
}

# Let us also imagine this variable is data from a user variable template.
variable "current_planet" {
  type = string
  default = "earth"
}

# how could I construct a variable that would give me access to the "earth_datacenter" credentials?
# I know we cannot do this syntax as it will throw an error.
output "planet_credentials" {
  value = var["${var.current_planet}_datacenter"]
}

#I tried to create a local to format the string to see if that could but it did not work either as it outputs the var as a string (as expected...grasping at straws here)

locals {
  planet_creds = format("var.%s_datacenter", var.current_planet)
}
output "planet_credentials" {
  value = local.planet_creds
}

# output is "var.earth_datacenter" not "earth credentials" as expected

I know I could leverage a data structure like a map and I'll be able to use string concatenation to get the value from the map, sadly this is not an option at the moment. Is this something that Terraform can even do? Would appreciate any help.


Solution

  • Is this something that Terraform can even do?

    You can't create dynamic variables. If you for some reason don't want to use maps or orther things are actually supported by TF, than maybe TF is the wrong match to your requirements.

    The only option is to create some wrapper around your TF code that will parse it and substitute all the names for variables.