Updated on 2023-12-13 GMT+08:00

Local Variables

Local values are like temporary variables in a module. Their application scope is in the declared module. They are declared by the keyword locals. Local variables can be helpful to reduce code redundancy and make code easy to modify in scenarios where the same values or expressions are repeatedly defined in the configuration. However, if local variables are overused, the actual values are hidden, making code hard to read by future maintainers. Therefore, use local variables properly.

Declaring Local Variables

Local variables are declared using the keyword locals.

locals {
  service_name = "forum"
  owner        = "Community"
}

Expressions of local variables are not limited to character and numeric constants. They can also use references and expression results of input variables, resource attributes, or other local values.

locals {
}

locals {
  common_tags = {
    Service = local.service_name
    Owner   = local.owner
  }
}

Referencing Local Variables

After declaring a local variable, you can use local.<Variable name> to reference it.

  ...
  tags = local.common_tags
}