Objective
By the end of this lab, you will have:
- Used locals to define a common tags set.
- Used locals to derive values from other values.
- Avoided the antipattern of locals for noise.
Requirements
- A Linux or macOS workstation with shell access.
- The Terraform CLI 1.9.x or later installed.
Scenario
You have a configuration that creates multiple files. Each file needs the same tags. The tags are defined in one place and applied to each file. The local is the way to define the shared tags.
Tasks
Task 1: Create the working directory
mkdir -p ~/rb-locals-lab
cd ~/rb-locals-lab
Task 2: Write the configuration
Create main.tf:
terraform {
required_version = ">= 1.9.0"
required_providers {
local = {
source = "hashicorp/local"
version = "~> 2.5"
}
}
}
variable "environment_name" {
type = string
default = "dev"
}
locals {
common_tags = {
Environment = var.environment_name
ManagedBy = "terraform"
Owner = "platform"
}
bucket_name = "data-${var.environment_name}"
domain = "${var.environment_name}.example.com"
}
resource "local_file" "greeting" {
filename = "${path.module}/greeting.txt"
content = "Hello!\n"
}
resource "local_file" "readme" {
filename = "${path.module}/readme.txt"
content = "Read me.\n"
}
resource "local_file" "config" {
filename = "${path.module}/config.txt"
content = <<EOF
bucket_name=${local.bucket_name}
domain=${local.domain}
EOF
}
Task 3: Apply the configuration
terraform init
terraform apply
Verify the files:
cat config.txt
The file content reflects the derived values.
Task 4: Modify the variable
Change the environment name:
terraform apply -var="environment_name=staging"
Verify the new file:
cat config.txt
The file content reflects the new variable.
Validation
The lab is successful if:
- The locals are defined once and used multiple times.
- The derived values are computed from the input variables.
- The plan is empty after the apply.
Expected Outcome
At the end of the lab:
+---------------------------------+
| ~/rb-locals-lab/ |
| .terraform/ |
| .terraform.lock.hcl |
| config.txt |
| greeting.txt |
| readme.txt |
| main.tf |
+---------------------------------+
The locals are documented in main.tf. The derived values
are in config.txt.
Cleanup
cd ~/rb-locals-lab
rm -rf .terraform *.txt main.tf
What You Learned
You learned the local pattern:
- Locals reduce duplication. A common tags set is one place.
- Locals express derived values. A derived value is documented once.
- Locals are not in the state. They are computed during the configuration phase.
- Locals are not exposed. They are computed inside the configuration.
- Avoid locals for noise. A local that just renames a variable is a tax.