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
Top comments (7)
The reason this works is due to Terraform
variable
values (and providers) do not support interpolation. The TFengine
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 theengine
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.
This is brilliant -> thank you!!!
I like it! realy useful while HCL does not not support interpolation in this way
Thanks, but this works only for outputs.
worked for for me with an ssm parameter value:
It woks in a resource section and in a output section but it does not work if try to set an input variable this way.
correct. this is a work around for similar functionality