Locals vs Variables: Understanding Scope and Purpose
Discover how local and global variables work, why scope matters, and how to choose the right one to write cleaner, bug-free code.
While seemingly simple, the distinction between locals and variables is a frequent source of confusion.
The Problem
# Attempting to use locals in variable defaults (DOESN'T WORK)
locals {
environment_prefix = substr(var.environment, 0, 1)
}
variable "resource_name" {
default = "${local.environment_prefix}-resource" # ERROR: Can't reference locals here
}
The Solution
# Proper use of variables and locals
variable "environment" {
type = string
}
variable "resource_name_prefix" {
type = string
default = "resource"
}
locals {
environment_prefix = substr(var.environment, 0, 1)
resource_name = "${local.environment_prefix}-${var.resource_name_prefix}"
}
resource "aws_s3_bucket" "example" {
bucket = local.resource_name
}
Locals are for internal calculations, while variables are for external inputs. Scalr's policy engine can help enforce this distinction by validating the structure of your code.