Local Values
Imagine you’re designing a Lego city with Terraform. You’ve already defined variables for the number of houses, the type of roofs, and the size of roads. But sometimes, you need a shortcut way to reuse a calculation or expression without repeating it everywhere.
That’s where local values come in. Locals are like sticky notes inside your configuration: quick references that simplify complex logic, reduce duplication, and make your code easier to read.
What are Local Values?
- Local values are named expressions you can reference within your configuration.
- They don’t accept external input (unlike variables).
- Think of them as internal shortcuts for simplifying code.
Declaring Locals
Locals are declared in a locals block:
locals {
instance_name = "web-server"
environment = "dev"
}
Using Locals
You reference locals with the local. prefix:
resource "aws_instance" "example" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
tags = {
Name = local.instance_name
Environment = local.environment
}
}
Practical Use Cases
- Tagging Resources: Define tags once, reuse everywhere.
- Simplifying Expressions: Store complex calculations in locals.
- Consistency: Ensure repeated values (like environment names) stay consistent.
- Readability: Make configurations easier to understand.
Hands‑On Lab / Demo
Lab: Using Locals for Tags
- Run:
terraform plan→ see tags applied from locals.terraform apply→ provision EC2 with consistent tags.
Create main.tf:
provider "aws" {
region = "us-east-1"
}
locals {
instance_name = "web-server"
environment = "dev"
}
resource "aws_instance" "example" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
tags = {
Name = local.instance_name
Environment = local.environment
}
}
Pro Tips & Best Practices
- Use locals for values that repeat across multiple resources.
- Keep locals organized in a dedicated
locals.tffile for clarity. - Don’t overuse locals - reserve them for simplifying code, not replacing variables.
- Combine locals with variables for maximum flexibility.
Summary & Cheatsheet
- Locals = Internal shortcuts.
- Declare in
localsblock. - Reference with
local.prefix. - Use cases: Tags, repeated values, simplifying logic.
Quick mnemonic: Locals = Simplify, Reuse, Readability
The Hackers Notebook
Local values make Terraform configurations cleaner and more maintainable. They reduce duplication, improve readability, and ensure consistency across resources. By mastering locals, you’ve learned how to simplify your code without sacrificing flexibility.
