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
var.xxx
in the same way shown ealierlocal.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:
data <type> <name> {...}
block data.<type>.<name>.<attribute>
in whatever resource needs it.Layer #5: A bit like the data blocks above, there are also output
blocks, which:
output <name> { ... }
blocks.tfvars
filesTF_VAR_*
env files