Terraform Variables and Resource Attributes

Posted: 07 September, 2021 Category: devops Tagged: terraform


HCL (Hashicorp Configuration language) is NOT the most aesthetically pleasing thing to look at. To make matters worse, there are a couple of layers of indirection as to how variables can be defined and used.

  • Layer #1: A top-level variables.tf file

    If only it could have entries like foo=123 or bar="four five six". Alas, NO. It takes 3 poxy lines to declare a variable, thusly:

    variable "my_var_name" {
      default = "its (default) value"
  • Layer #2: A locals block, in your main.tf file. eg:

    locals {
      # note string interpolation
      foobar = "foo-${var.my_var_name}-bar"
      # also a good place to define a bunch of resuable tags / tag lexemes
      common_tags = {
        Environment = terraform.workspace
        Project     = var.project
        ManagedBy   = "Terraform"

    Besides the terraform.workspace freebie populated by terraform itself, note that var.* refers to a variable defined in the variables.tf file.

  • Layer #3: Using values in the rest of your .tf files

    • use var.xxx in the same way shown ealier
    • use local.xxx (note the unexpected singular: local.xxx, NOT locals.xxx) to reference items in main.tf locals {}.
  • Layer #4: Use data blocks to fetch info about resources; each resource type:

    • is defined as data <type> <name> {...} block
    • furnishes a bunch of useful data exposed as a list of values.
    • These values are referenced as data.<type>.<name>.<attribute> in whatever resource needs it.
  • Layer #5: A bit like the data blocks above, there are also output blocks, which:

    • are defined as output <name> { ... } blocks
    • yield resource attributes after a resource has been created... i.e. attributes like assigned IP addresses and such, which we can have no way of knowing until the resource exists.
  • Layer #6: .tfvars files

  • Layer #7: any TF_VAR_* env vars that terraform finds floating about in its environment