Search code examples
terraform

Difference between var="${local.var}" and var=local.var in the context of invoking a module


Let's say we have a local variable called var and we want to pass it to a child module as in put variable, what is the way to do it?

module "mod1" {
  source = "..."
  var = local.var
}

or

module "mod1" {
  source = "..."
  var = "${local.var}"
}

Why do we choose the second method at all? I understand that the construct ${local.var} is useful if we are building another string with the value of the local variable. However, what is the significance of var = "${local.var}"?


Solution

  • A ${ ... } sequence is an interpolation, which evaluates the expression given between the markers, converts the result to a string if necessary, and then inserts it into the final string:

    "Hello, ${var.name}!"
    

    In your case, using the interpolation makes no sense because the result will be the same. Also, the extra chars "${ ... }" makes the code slightly less readable.

    You can quickly remove redundant string interpolations in your Terraform configuration files by running terraform fmt, which applies a subset of the Terraform language style conventions, along with other minor adjustments for readability (e.g. fix the indentation).

    Considering the following Terraform code:

    module "mod1" {
      source = "..."
    
      var    = "${local.var}"
    }
    

    Running terraform fmt -diff code will be changed to:

    module "mod1" {
      source = "..."
    
      var = local.var
    }
    

    Output of the command:

    main.tf
    --- old/main.tf
    +++ new/main.tf
    @@ -1,5 +1,5 @@
     module "mod1" {
       source = "..."
     
    -  var    = "${local.var}"
    +  var = local.var
     }
    \ No newline at end of file
    

    Consider using the -recursive to process files in subdirectories as well. See the documentation for more details.