Local Values and Computed Attributes
What you'll learn: How to simplify complex expressions with local values and understand resource attributes that Terraform computes automatically.
What Are Local Values?
Think of local values as temporary variables you create inside your configuration to avoid repeating complex expressions. They work like shortcuts—you calculate something once using locals blocks, then reference it multiple times without duplicating logic.
locals {
common_tags = {
Environment = "production"
ManagedBy = "terraform"
}
instance_name = "${var.project_name}-web-server"
}
resource "aws_instance" "web" {
ami = "ami-12345"
instance_type = "t2.micro"
tags = local.common_tags
}
resource "aws_ebs_volume" "data" {
size = 10
tags = merge(local.common_tags, {
Name = "${local.instance_name}-data"
})
}
Notice how local.common_tags and local.instance_name make the code cleaner and easier to maintain.
What Are Computed Attributes?
Computed attributes are values that Terraform or the cloud provider determines after creating a resource. You don't set them—you read them.
resource "aws_instance" "web" {
ami = "ami-12345"
instance_type = "t2.micro"
}
output "instance_ip" {
value = aws_instance.web.public_ip # Computed by AWS
}
output "instance_id" {
value = aws_instance.web.id # Computed by AWS
}
You can't know the public_ip or id until AWS creates the instance. These are computed at apply time, not when you write the config.
Why This Matters
Locals reduce repetition and centralize logic. Computed attributes let you reference real infrastructure values created by providers. Together, they make configurations dynamic and maintainable.
Key Takeaway: Use locals to simplify repeated expressions; rely on computed attributes to reference provider-generated values like IDs and IPs after resource creation.