How to create one variable from another variable in terraform variable.tf file?

Viewed 5869

For example, In variable.tf file we have a code like below

variable "variable1" {
    type    = string
    default = "ABC"
}

variable "variable2" {
    type    = string
    default = "DEF"
}

variable "variable3" {
    type    = string
    default = "$var.variable1-$var.variable2"
}

Expected output :

variable3 = ABC-DEF

4 Answers

Yes, I agree with @Montassar, you can use the local block to create a new expression from the existing resources or the variables. But it should combine the variables like this:

locals {
  variable3 = "${var.variable1}-${var.variable2}"
}

And it will look like this:

enter image description here

To my knowledge what you want is not doable with default.

However you can create variable3 and just not assign it a default value and then in your call set variable3 = var.variable1-var.variable2

Not sure this solves your problem but to my knowledge the way you want to do it, won't work.

Also I would recommend upgrading to v0.12.

You can't do this. Docs clearly states:

The default argument requires a literal value and cannot reference other objects in the configuration.

But you could probably use locals for variable3.

Related