Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 37 ยท Variables, Outputs and Data Sources

Local Values and Outputs

Use Terraform locals to name and reuse expressions and outputs to expose results: syntax, sensitive and described outputs, terraform output -json and -raw, and module outputs.

Two small block types complete the "function" picture of a module. Local values are the module's temporary variables: names for expressions you use more than once. Output values are its return values: the information you want to see after an apply, or hand to another module or another Terraform configuration. Both are tiny, but they shape how readable and reusable your code is.

HCL is read-only; the Python stand-ins evaluate locals in dependency order and render outputs.

Local values

Declare locals in a locals block (any number of blocks, in any file) and read them with local.name (singular):

HCL
locals {
  project     = "shop"
  environment = terraform.workspace
  name_prefix = "${local.project}-${local.environment}"

  common_tags = {
    Project     = local.project
    Environment = local.environment
    ManagedBy   = "terraform"
  }

  is_prod = local.environment == "prod"
}

resource "aws_s3_bucket" "logs" {
  bucket = "${local.name_prefix}-logs"
  tags   = merge(local.common_tags, { Purpose = "logs" })
}

Locals may refer to variables, resources, data sources, functions and other locals; Terraform works out the order. The one rule: no cycles (a uses b, b uses a).

Locals versus variables

Variable Local
Set by The caller (CLI, tfvars, module block) The module itself
Purpose An input A computed helper
Visible as var.x local.x
Can be overridden from outside Yes No

If a value should be configurable, make it a variable. If it is derived, give it a local. A frequent mistake is making everything a variable: the interface of your module gets huge and users must supply values that should be calculated.

What locals are good for

  • Names: build "${var.project}-${var.environment}-api" once and reuse it.
  • Tags: one common_tags map merged into every resource.
  • Data reshaping: turn a list into a map for for_each once, then use it everywhere.
  • Naming complex conditions: local.is_prod reads better than repeating var.environment == "prod".
  • Defaults derived from other inputs: local.zone_count = coalesce(var.zone_count, length(data.aws_availability_zones.all.names)).

Do not overuse them. A local used once is just indirection, unless its name explains a complicated expression.

Python Evaluating locals in dependency order (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The definitions appear out of order in the dictionary (bucket last, environment first only by luck), yet evaluation works, as it does in Terraform. Two locals that need each other are a cycle, an error.

Output values

An output exposes a value from a module:

HCL
output "instance_ip" {
  description = "Public IP address of the web server."
  value       = aws_instance.web.public_ip
}

output "db_endpoint" {
  value     = aws_db_instance.main.endpoint
  sensitive = true
}

After terraform apply, outputs of the root module are printed and stored in state:

TEXT
Outputs:

db_endpoint = <sensitive>
instance_ip = "203.0.113.17"

(Example output.) Settings:

Setting Purpose
value The expression to expose (required)
description Documentation; always write one
sensitive Hide in CLI output (required if the value derives from a sensitive input)
depends_on Rarely needed; adds an explicit dependency
precondition Assert something before the output is accepted
ephemeral Not stored in state (Terraform 1.10+, for child modules)

Reading outputs

Terminal
terraform output                      # all outputs
terraform output instance_ip          # one, with quotes for strings
terraform output -raw instance_ip     # raw string for shell scripts
terraform output -json                # machine-readable JSON

-raw is ideal in scripts and pipelines: ssh ubuntu@$(terraform output -raw instance_ip). -json suits tools such as jq. Sensitive outputs are redacted in the plain CLI view, but terraform output -json and -raw print them and they are in the state file, so treat access accordingly.

Outputs of structured values

An output can be any type. Return a map to give consumers every ID by key:

HCL
output "server_ips" {
  value = { for name, s in aws_instance.app : name => s.private_ip }
}

output "subnet_ids" {
  value = aws_subnet.private[*].id
}

Return whole objects when consumers need several related attributes together: one database output with { endpoint, port, name } is tidier than three separate outputs.

Python Rendering outputs, including sensitive ones (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Module outputs

Child modules return data to their caller only through outputs. The caller reads them as module.<name>.<output>:

HCL
module "network" {
  source = "./modules/network"
  cidr   = "10.0.0.0/16"
}

resource "aws_instance" "web" {
  subnet_id = module.network.private_subnet_ids[0]
}

Everything not exported by an output is invisible to the caller. Design module outputs as a stable interface: expose IDs and ARNs that callers need, not every internal attribute. Modules get their own chapter.

Sharing outputs between configurations

Large infrastructures split into several root configurations (network, data, apps). The apps need the network's subnet IDs. Two approaches:

  • terraform_remote_state data source reads another configuration's outputs from its state, which couples you to that state location and gives read access to the whole state.
  • Publish and look up: store values in a parameter store, or use data sources that find the resources by tag or name (data sources). This is looser and generally preferred.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you reference a local value named name_prefix?

    The block is locals (plural) but references use local (singular): local.name_prefix.
  2. 2. Which command prints an output as a plain string suitable for shell scripts?

    terraform output -raw prints the string without quotes or formatting, ready for command substitution.
  3. 3. An output derived from a sensitive variable must be...

    Terraform refuses to expose a sensitive-derived value unless the output is explicitly marked sensitive.
  4. 4. When should a value be a local rather than a variable?

    Variables are inputs. Locals are internal helper values computed from inputs, resources and other locals.

Summary

  • locals give names to repeated or complex expressions; reference them as local.name; cycles are errors.
  • Make a value a variable if callers should set it, a local if it is derived.
  • output blocks return values from a module; root outputs print after apply and live in state.
  • Use description and sensitive; read with terraform output, -raw and -json.
  • Child module outputs are the module's public interface, read as module.name.output.
  • Prefer looser coupling (data lookups) over terraform_remote_state when sharing across configurations.

Next: Data Sources