Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 209
Venki Avatar asked Dec 14 '22 08:12

Venki


2 Answers

you can use local instead

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

and then to call it instead of using var. use local. like this!

resource "example" "example" {

   example = local.variable3

}

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

like image 136
Montassar Bouajina Avatar answered Dec 15 '22 22:12

Montassar Bouajina


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

like image 42
Charles Xu Avatar answered Dec 15 '22 21:12

Charles Xu