Lesson 04 beginner

Terraform Variables and Outputs

Make one configuration serve every environment with typed input variables, validation rules, locals and outputs, and learn the modern options: sensitive and ephemeral values, deprecation warnings, typed outputs and const variables.

The configuration from lesson 3 hard-codes everything: the container name, the port, the image tag. To run Orbit as dev on your laptop and as staging on a shared host from the same code, you need inputs (variables), internal names for repeated expressions (locals) and results other people and tools can read (outputs).

Declaring input variables

Create variables.tf next to main.tf. Splitting files by purpose is a convention, not a rule: Terraform reads every .tf file in the folder as one configuration.

variable "environment" {
  description = "Deployment name, used in every resource name."
  type        = string
}

variable "web_port" {
  description = "Port on the host where the web container listens."
  type        = number
  default     = 8080
}

variable "web_image_tag" {
  description = "nginx image tag for the front end."
  type        = string
  default     = "1.27-alpine"
}

variable "labels" {
  description = "Extra labels added to every container."
  type        = map(string)
  default     = {}
}

Use them with var.<name>:

resource "docker_image" "web" {
  name = "nginx:${var.web_image_tag}"
}

resource "docker_container" "web" {
  name  = "orbit-${var.environment}-web"
  image = docker_image.web.image_id

  ports {
    internal = 80
    external = var.web_port
  }
}

A variable without a default is required: plan stops and asks for it. Always write a description; it is the only documentation most people will read.

Types

TypeExample value
string"staging"
number8080
booltrue
list(string)["web", "api"]
set(string)like a list, unordered and without duplicates
map(number){ web = 8080, api = 9090 }
object({...})a record with named, typed attributes
tuple([...])a fixed-length list with a type per position

Objects can mark attributes as optional with a default, which keeps callers’ inputs short:

variable "cache" {
  type = object({
    enabled   = bool
    memory_mb = optional(number, 128)
    image     = optional(string, "valkey/valkey:8-alpine")
  })
  default = { enabled = true }
}

Validation rules

Catch bad input at plan time with a message a human understands, instead of a cryptic API error halfway through apply:

variable "environment" {
  type = string

  validation {
    condition     = contains(["dev", "staging", "prod"], var.environment)
    error_message = "environment must be dev, staging or prod."
  }
}

variable "api_port" {
  type    = number
  default = 9090

  validation {
    condition     = var.api_port != var.web_port
    error_message = "api_port and web_port must be different."
  }
}

Since Terraform 1.9, a validation rule can refer to other variables and even data sources, like the api_port check above. Before 1.9 it could only look at its own variable.

Giving variables values

Terraform reads values from several places. When the same variable is set more than once, the later source in this list wins:

  1. The default in the declaration
  2. Environment variables named TF_VAR_<name>
  3. terraform.tfvars (and terraform.tfvars.json), loaded automatically
  4. Any *.auto.tfvars files, in alphabetical order
  5. -var-file=... and -var name=value on the command line, in the order you type them

The usual layout is one file per environment:

# staging.tfvars
environment = "staging"
web_port    = 8181
labels = {
  team = "orbit"
  cost = "shared-host"
}
$ terraform plan -var-file=staging.tfvars
$ TF_VAR_web_port=8282 terraform plan -var-file=staging.tfvars

In the second command, staging.tfvars wins over the environment variable, because command-line files come later in the list. That surprise catches everyone once.

Locals: names for expressions

Locals are values computed inside the configuration. Use them to avoid repeating the same expression:

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

  common_labels = merge(
    { app = "orbit", environment = var.environment, managed_by = "terraform" },
    var.labels,
  )
}

resource "docker_container" "web" {
  name  = "${local.name_prefix}-web"
  image = docker_image.web.image_id

  dynamic "labels" {
    for_each = local.common_labels
    content {
      label = labels.key
      value = labels.value
    }
  }
}

(The dynamic block is covered in lesson 10.) Rule of thumb: a variable is something the caller decides, a local is something the code derives.

Outputs

Outputs print useful values after apply and let other configurations and scripts read them:

output "web_url" {
  description = "URL of the Orbit front end."
  value       = "http://localhost:${var.web_port}"
}

output "container_ids" {
  type = map(string)
  value = {
    web = docker_container.web.id
  }
}

The type argument on outputs is new in Terraform 1.15. It documents the shape and makes Terraform convert, or fail loudly, if the value does not match.

$ terraform output
container_ids = {
  "web" = "6f1c2e..."
}
web_url = "http://localhost:8181"
$ terraform output -raw web_url
http://localhost:8181
$ terraform output -json container_ids
{"web":"6f1c2e..."}

-raw is for shell scripts (curl "$(terraform output -raw web_url)"), -json for anything that parses.

Sensitive and ephemeral values

Orbit pulls a private image from a registry, which needs a password. There are two levels of protection:

  • sensitive = true hides the value in plan and apply output. It is still stored in the state file in plain text.
  • ephemeral = true (Terraform 1.10+) means the value is never written to state or to a plan file at all. You can only use it in places that do not persist: provider configuration, other ephemeral values and write-only arguments (lesson 15).

The registry password is only needed by the provider to log in, so it can be ephemeral:

variable "registry_password" {
  type      = string
  sensitive = true
  ephemeral = true
}

provider "docker" {
  registry_auth {
    address  = "ghcr.io"
    username = "orbit-ci"
    password = var.registry_password
  }
}
$ export TF_VAR_registry_password="$(cat ~/.secrets/ghcr-token)"
$ terraform plan

Never put secrets in a committed .tfvars file. Pass them through environment variables or a secret manager.

Evolving variables safely

Two Terraform 1.15 additions help when a configuration is shared with other people.

Deprecation. You want to rename web_image_tag to web_image. Instead of breaking every caller, mark the old one:

variable "web_image_tag" {
  type       = string
  default    = null
  deprecated = "Use web_image instead. web_image_tag will be removed in March."
}

Anyone who still sets it gets a warning in plan, with your message. Outputs accept the same deprecated argument.

Const variables. Normal variables are only known at plan time, which is too late for decisions made during terraform init, such as where to download a module from. A variable marked const = true is resolved during init and can be used in a module source or version:

variable "cache_flavour" {
  type  = string
  const = true
}

Lesson 6 shows it in a module. A const variable cannot also be sensitive or ephemeral.

Quick reference

TaskSyntax or command
Use a variablevar.environment
Use a locallocal.name_prefix
Set a value from a fileterraform plan -var-file=staging.tfvars
Set one valueterraform plan -var="web_port=8181"
Set from the environmentTF_VAR_web_port=8181
Show all outputsterraform output
One output for a scriptterraform output -raw web_url
Output as JSONterraform output -json
Hide a value in the CLIsensitive = true
Keep a value out of state (1.10)ephemeral = true
Warn callers about an old input (1.15)deprecated = "message"

Exercise

web_port has default 8080. terraform.tfvars sets it to 8181 and you run terraform plan -var=”web_port=9000″. Which value is used?

  1. 8080, because the declaration has the final word
  2. 8181, because terraform.tfvars is loaded last
  3. 9000, because command-line values are applied after every file and the default
  4. Terraform stops with an error about a duplicate value
Show answer

Answer: C. Defaults are the weakest source and command-line -var and -var-file are the strongest. Within the command line, the last flag you typed wins.

Exercise

A database password variable is marked sensitive = true. Where can the password still be found?

  1. Nowhere, sensitive values are encrypted everywhere
  2. Only in the terminal output of terraform apply
  3. In the state file and in saved plan files, in plain text
  4. Only in HCP Terraform’s audit log
Show answer

Answer: C. sensitive only redacts CLI output. The value is still stored in state and plans. To keep a secret out of both, use ephemeral values and write-only arguments (Terraform 1.10 and 1.11+).

Key takeaways

  • Variables are inputs, locals are derived names, outputs are results.
  • Always set a type and a description; use optional() to keep object inputs short.
  • Validation rules turn bad input into clear errors at plan time, and can compare variables since 1.9.
  • Later sources win: default, TF_VAR_, terraform.tfvars, *.auto.tfvars, then the command line.
  • sensitive hides values from the screen; ephemeral keeps them out of state and plans.
  • Use deprecated (1.15) to rename inputs and outputs without breaking callers.

FAQ

Should I commit .tfvars files?

Commit the ones that hold only non-secret settings, such as staging.tfvars with ports and sizes. They are part of your infrastructure’s definition. Keep secrets out of them and pass those through environment variables or a secret manager.

Why can’t I use a variable in the backend block?

The backend is configured during terraform init, before variables are evaluated. Use partial backend configuration instead: terraform init -backend-config=staging.s3.tfbackend. Lesson 5 shows how.

What is the difference between a local and a variable with a default?

A caller can override a variable; nobody can override a local. If a value should never change between environments, a local stops people from changing it by accident.

Can outputs be used by another Terraform configuration?

Yes. A child module’s outputs are read with module.<name>.<output>. Between separate root configurations, use the terraform_remote_state data source or, better, publish the value somewhere both can read (a parameter store, HCP Terraform outputs). Lesson 7 discusses the trade-offs.

↑ ↓ navigate Enter open Esc close