Lesson 3 of 4 ยท Terraform Core Concepts
Locals and data sources
Locals name expressions used repeatedly inside one configuration. Data sources read infrastructure that already exists instead of creating it. Both reduce duplication, but they solve different problems: locals calculate; data sources look up.
Example
locals {
name_prefix = "training-${var.environment}"
}
data "aws_region" "current" {}
output "region" {
value = data.aws_region.current.name
}Step by step
- Use a local for a repeated expression.
- Use a data source for something Terraform should read.
- Keep data-source filters specific.
- Reference locals with local.name.
Common mistakes to avoid
- Using a local to hide a complex but unclear expression.
- Using a broad data-source lookup that could select the wrong resource.