loading...

Terraform: use a variable's value to define another variable

drewmullen profile image drewmullen Updated on ・1 min read

I was looking for a way to set a default terraform variable value from another variable but also have a way to override. Terraform does not allow this natively:

variable nickname {
  default = var.fullname
}

variable fullname {
  default = "richard"
}

output name {
  value = var.nickname
}

$ terraform apply

Error: Variables not allowed

  on var-to-var.tf line 2, in variable "nickname":
   2:   default = var.fullname

Variables may not be used here.

But I was able to get this working, see below!

Disclaimer: This does not technically default the value from one variable to another. However, it provides the desired output; at least the one I was looking for.

variable fullname {
  default = "richard"
}

variable nickname {
  default = ""
}

output name {
  value = var.nickname != "" ? var.nickname : var.fullname
}
terraform apply
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
Outputs:
name = richard
terraform apply -var nickname=drew
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
Outputs:
name = drew

Posted on by:

drewmullen profile

drewmullen

@drewmullen

Full-stack YAML engineer

Discussion

pic
Editor guide
 

The reason this works is due to Terraform variable values (and providers) do not support interpolation. The TF engine is not yet running when the values are assigned.

outputs on the other hand are evaluated near the end of a TF life cycle. Thus the engine is running and interpolation is supported.

Another way to to this is use a null object and apply the value = "${var.nickname != "" ? var.nickname : var.fullname}" logic to it.

Side note; might want to check out upgrading the TF 0.12.x when you get a chance. The resource/var/output sytax changes a bit.

 

I like it! realy useful while HCL does not not support interpolation in this way