Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference map in locals in terraform file

Tags:

terraform

In a tvfars file I have this:

locals {
    common = {
        "my key" = "value"
    }
}

because I want to use the map in multiple places in that file. I read the terraform docs about variables and I cannot find the correct syntax. I tried the following (var1 and 2 are both declared as maps):

  1. With

    var1 = "${local.common}"
    var2 = "${local.common}"
    

    I get

    variable "var1" should be type map, got string
    
  2. With

    var1 = locals.common
    var2 = locals.common
    

    I get

    invalid value "myfile.auto.tfvars" for flag -var-file-default: Error parsing myfile.auto.tfvars: At 18:15: Unknown token: 18:15 IDENT locals.common
    
  3. With

    var1 = {"${local.common}"}
    var2 = {"${local.common}"}
    

    which fails without an error message but a print of terraform help and terraform exits.

I verified that everything works fine if I copy/paste the map multiple times:

var1 = {
     "my key" = "value"
}
var2 = {
     "my key" = "value"
}

Anyone know correct syntax?

like image 913
Oliver Avatar asked Oct 18 '25 05:10

Oliver


1 Answers

local blocks,interpolations and expressions that are not constants cannot be used in terraform.tfvars file.

See github-issue for further dicussion

The way around is to define the variable only once in terraform.tfvars and make the duplicate variables local in the terraform module file.

Example:

variable.tf

variable var1 { type = "map" }

terraform.tfvars

var1= { "key1" = "value1", "key2" = "value2" }

module.tf

 locals {  
    var2="${var.var1}"  
 }  

 output show_var2 {
    value = "${local.var2}"
 }
like image 75
keety Avatar answered Oct 22 '25 03:10

keety