Skip to Content

Terraform Field Guide · Chapter 4 of 12

Variables, outputs and locals

Hard-coded values make a configuration that builds exactly one thing. Variables let the same code build dev and prod, locals keep the logic in one place, and outputs hand results to people and other code. Includes the exact order Terraform uses when a value is set in more than one place.

  • 40 min
  • Intermediate
  • Hands-on
  • Free

By , founding engineer running Terraform in production. Updated .

dev.tfvarssize = "small"prod.tfvarssize = "large"one configurationvariable "size"locals { … }resource …output "url"dev1 × t3.smallurl = dev.example.comprod3 × m5.large, 3 AZsurl = example.comSame code, different inputsvariables in, outputs out, locals in between
The chapter in one pictureOne configuration, different inputs. Variables go in, outputs come out, locals tidy up the middle.

By the end you can

0 of 5

Variables

A configuration with "t3.small" written into it builds one thing. Replace the value with a variable and the same code can build a small dev environment and a large production one. Variables are the inputs to your configuration, declared by convention in variables.tf:

variables.tf
variable "environment" {
  type        = string
  description = "Which environment this is: dev, staging or prod."

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

variable "instance_type" {
  type    = string
  default = "t3.micro"
}

variable "allowed_cidrs" {
  type    = list(string)
  default = []
}

variable "db_password" {
  type      = string
  sensitive = true
}
Types catch mistakes early: string, number, bool, list(...), map(...), and object({...}) for structured inputs.
Shows up in errors and in generated docs. Write one for every variable; future you is the reader.
A rule checked before planning. Turns "production" vs "prod" from a strange half-built environment into a clear error.
Optional. A variable with no default is required: Terraform asks for it, or fails in CI.
Redacted in plan output. Still stored in state.

Setting values

There are several ways to give a variable a value, and in real projects more than one is often in play at once. Terraform resolves them in a fixed order, where each later source overrides the earlier ones. Turn sources on and off:

Interactive · Which value wins?

var.instance_type is set in six places

    In practice you use three of these:

    • A tfvars file per environment, such as dev.tfvars and prod.tfvars, passed with -var-file. Reviewed in Git like everything else.
    • Environment variables (TF_VAR_name) for values that come from CI, such as a build number.
    • Defaults for anything that is the same everywhere.

    Avoid -var for anything that matters: it lives in someone's shell history, not in Git, so the next person cannot reproduce the apply.

    Locals

    A local is a named expression inside the configuration. Callers cannot set it; you use it to compute something once and reuse it. The classic uses are naming, sizing tables and tags:

    main.tf
    locals {
      name = "shop-${var.environment}"
    
      sizes = {
        dev     = { instance_type = "t3.small", count = 1 }
        staging = { instance_type = "t3.medium", count = 2 }
        prod    = { instance_type = "m5.large", count = 3 }
      }
      size = local.sizes[var.environment]
    
      tags = {
        environment = var.environment
        managed_by  = "terraform"
      }
    }
    
    resource "aws_instance" "web" {
      count         = local.size.count
      instance_type = local.size.instance_type
      ami           = "ami-0c55b159cbfafe1f0"
      tags          = merge(local.tags, { Name = "${local.name}-web-${count.index}" })
    }
    One naming rule, used everywhere. Change it here and every resource follows.
    A lookup table: each environment's size is data, not if-statements spread across files.
    Pick this environment's row. Validation on var.environment guarantees the key exists.
    Combine the shared tags with one resource's own. merge is one of many built-in functions.
    With count, each copy gets an index: 0, 1, 2.

    Outputs

    Outputs are the return values of a configuration. They print after apply, can be read with terraform output, and are how one module hands values to another (chapter 6).

    outputs.tf
    output "web_private_ips" {
      description = "Private IPs of the web instances."
      value       = aws_instance.web[*].private_ip
    }
    
    output "db_password" {
      value     = var.db_password
      sensitive = true
    }
    A splat: the private_ip of every instance created with count, as a list.
    Required when an output uses a sensitive value. Shown as (sensitive value) unless you ask for it by name.
    Reading outputs
    terraform output
    terraform output -raw db_password
    terraform output -json web_private_ips
    db_password = <sensitive>
    web_private_ips = [
      "10.0.1.24",
      "10.0.2.31",
    ]
    correct-horse-battery-staple
    ["10.0.1.24","10.0.2.31"]
    -raw
    Prints a single string without quotes, for scripts. It prints sensitive values too, so mind your terminal history.
    -json
    Machine-readable. Pipe it to jq, or read it in CI.

    Expressions

    HCL has a small expression language. These cover most real configurations:

    ExpressionExample
    String template"shop-${var.environment}"
    Conditionalvar.environment == "prod" ? 3 : 1
    For expression[for n in var.names : upper(n)]
    Map lookuplocal.sizes[var.environment]
    Functionsmerge(), lookup(), cidrsubnet(), jsonencode()

    Try any of them without writing a file: terraform console opens a prompt that evaluates expressions against your configuration.

    terraform console
    terraform console
    > cidrsubnet("10.0.0.0/16", 8, 2)
    "10.0.2.0/24"
    > [for n in ["web", "api"] : "shop-${n}"]
    [
      "shop-web",
      "shop-api",
    ]
    > merge({ a = 1 }, { b = 2 })
    {
      "a" = 1
      "b" = 2
    }
    cidrsubnet
    Carves a subnet out of a network range. You will use it to lay out VPC subnets without arithmetic.
    exit
    Type exit or press Ctrl+D to leave.

    Hands-on: one config, two environments

    Back to the local provider. This configuration writes an app config file whose contents depend on the environment.

    main.tf
    terraform {
      required_providers {
        local = { source = "hashicorp/local", version = "~> 2.5" }
      }
    }
    
    variable "environment" {
      type = string
    
      validation {
        condition     = contains(["dev", "staging", "prod"], var.environment)
        error_message = "environment must be dev, staging or prod."
      }
    }
    
    variable "replicas" {
      type    = number
      default = 1
    }
    
    locals {
      name = "shop-${var.environment}"
      config = jsonencode({
        name     = local.name
        replicas = var.replicas
        debug    = var.environment != "prod"
      })
    }
    
    resource "local_file" "config" {
      filename = "${path.module}/out/${local.name}.json"
      content  = local.config
    }
    
    output "config_file" {
      value = local_file.config.filename
    }
    Required: no default. Terraform will ask for it, or you pass it.
    A boolean expression: debug on everywhere except production.
    Turns an HCL object into JSON text. Safer than building JSON by hand in a string.
    Create two tfvars files
    echo 'environment = "dev"' > dev.tfvars
    printf 'environment = "prod"\nreplicas    = 3\n' > prod.tfvars
    
    Apply dev, then try prod
    terraform init
    terraform apply -var-file=dev.tfvars -auto-approve
    cat out/shop-dev.json
    terraform plan -var-file=prod.tfvars
    Outputs:
    
    config_file = "./out/shop-dev.json"
    
    {"debug":true,"name":"shop-dev","replicas":1}
    
      # local_file.config must be replaced
    -/+ resource "local_file" "config" {
          ~ filename = "./out/shop-dev.json" -> "./out/shop-prod.json" # forces replacement
    
    Plan: 1 to add, 0 to change, 1 to destroy.
    -var-file=dev.tfvars
    Loads that file's values. Swap the file and the same code describes a different environment.
    1 to destroy
    Look closely: planning prod would delete dev. One state file can only hold one environment. Chapter 7 gives each environment its own state.

    Do not apply that plan. Instead, prove validation works:

    A typo in the environment name
    terraform plan -var 'environment=production'
    │ Error: Invalid value for variable
    │
    │   on main.tf line 7:
    │    7: variable "environment" {
    │     ├────────────────
    │     │ var.environment is "production"
    │
    │ environment must be dev, staging or prod.

    Mini mission

    Guard the inputs and add an output

    Add a validation so replicas must be between 1 and 10. Then add an output called summary that prints something like shop-dev runs 1 replica(s), debug on. Check both with terraform plan -var-file=dev.tfvars -var replicas=20 and a normal apply.

    Reveal one safe solution
    main.tf
    variable "replicas" {
      type    = number
      default = 1
    
      validation {
        condition     = var.replicas >= 1 && var.replicas <= 10
        error_message = "replicas must be between 1 and 10."
      }
    }
    
    output "summary" {
      value = "${local.name} runs ${var.replicas} replica(s), debug ${var.environment != "prod" ? "on" : "off"}"
    }

    With replicas=20, plan stops with your error message. A normal apply prints the summary under Outputs:. The conditional inside the template is the same ? : expression from the table above.

    Check yourself

    Quiz

    0 of 5 answered

    1. 1. A variable is set in terraform.tfvars and with -var on the command line. Which wins?
    2. 2. What does sensitive = true on a variable do?
    3. 3. When would you use a local instead of a variable?
    4. 4. Someone passes environment = "production" and the variable has a validation of dev, staging or prod. What happens?
    5. 5. Which file is loaded automatically without a flag?

    Further reading