Terraform Variables and Resource Attributes

Posted: 07 September, 2021 Category: rough notes Tagged: terraform

Variables

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.