How to define default value of one variable based on other variables in Terraform variable.tf file?

11.5k views Asked by At

For example, in variable.tf file we have this code:

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
5

There are 5 answers

9
Charles Xu On BEST ANSWER

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

1
Berimbolinho On

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.

0
Marcin On

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.

0
Montassar Bouajina On

You can use local instead

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

and then instead of using var. use local. like this:

resource "example" "example" {

   example = local.variable3

}

ref : https://www.terraform.io/docs/configuration/locals.html

0
sborsky On

Assuming the intended effect of the "default value" being that it is used only if the user did not provide a value - here is a more complete example:

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

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

variable "variable3" {
    type    = string
    default = ""
}    

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