Terraform configuration ยท 11 min read

Variables, locals, and outputs

Variables receive input, locals name reusable expressions inside a module, and outputs expose useful results. Keeping those roles separate makes a configuration easier to reuse and review.

Inputs, internal expressions, and results

The three blocks show the different jobs of a variable, local, and output in one small configuration.

variable "environment" { type = string }

locals { name_prefix = "training-${var.environment}" }

output "network_id" { value = aws_vpc.main.id }

Variables are a contract

A variable tells a caller what value they may provide. Types and validation can reject obvious mistakes before Terraform contacts a provider, such as a malformed collection or unsupported environment name.

Use defaults only when they are safe and unsurprising. Account-specific identifiers and secrets should arrive through protected inputs, not committed examples.

Locals are internal names

Locals are useful for consistent prefixes, calculated tag maps, and expressions used in multiple places. A resource reference inside a local still creates a dependency, so do not overlook hidden references while debugging.

Avoid turning every expression into a local. If a reader must jump across many definitions to understand one resource, the abstraction has become too dense.

Outputs are results

Outputs expose values another person, module, or system genuinely needs, such as a network ID or load balancer hostname. Keep the interface small and understandable.

Sensitive output limits display in normal Terraform output; it does not remove the need for secure state storage and controlled access.

Put it into practice

Add an environment variable, calculate a name prefix with a local, and output one resource ID. Decide which values should remain internal.

  1. Give inputs clear names and appropriate types.
  2. Use locals for repeated expressions, not hidden logic.
  3. Expose only useful results as outputs.
  4. Keep secrets out of source code and mark sensitive outputs.