Variables, Locals, Outputs, and Expressions

Make one Terraform configuration serve dev, staging and prod with typed input variables, validation, locals, outputs, for expressions and built-in functions.

By The Dark DebuggerUpdated 25 min read

This tutorial turns the hard-coded configuration from the Terraform Introduction into one you can reuse: typed input variables with validation, every way of setting them (and which one wins), local values, outputs, and the expression language that glues them together. You should have Terraform installed and know the init, plan, apply loop. Everything runs locally; the only download is the small hashicorp/local provider, which writes files.

Why this matters

Picture a checkout service that runs in dev, staging and production. The three environments are almost identical: production has more replicas, a quieter log level, longer log retention and a few extra labels for the on-call rota. Without variables you copy the configuration three times, and within a month the copies have drifted: someone bumped the port in dev and forgot prod, or fixed a typo in only one of them.

Variables fix that. You write the configuration once, declare the handful of things that genuinely differ as inputs, and feed in a different set of values per environment. Terraform checks types and your validation rules before it touches anything, so environment = "production" fails at plan time, not at 2 a.m.

The example project

Terraform will render the configuration files for the checkout service: a JSON settings file, an nginx upstream block, and a secrets file for the database password. Real teams do exactly this with cloud resources; here the "infrastructure" is files, so you can inspect every result with cat.

tree
.
├── main.tf
├── outputs.tf
├── templates
│   └── upstream.conf.tftpl
└── variables.tf

Terraform loads every .tf file in the directory, so splitting declarations into variables.tf, main.tf and outputs.tf is purely a convention. It's the one most teams use, because it makes inputs and outputs easy to find.

Declaring input variables

Here is the complete variables.tf. The sections below explain each feature it uses.

variable "environment" {
  description = "Deployment environment: dev, staging or prod"
  type        = string
  default     = "dev"
 
  validation {
    condition     = contains(["dev", "staging", "prod"], var.environment)
    error_message = "environment must be one of: dev, staging, prod."
  }
}
 
variable "replicas" {
  description = "How many app instances sit behind the load balancer"
  type        = number
  default     = 2
 
  validation {
    condition     = var.replicas >= 1 && var.replicas <= 10
    error_message = "replicas must be between 1 and 10."
  }
}
 
variable "service" {
  description = "The service being deployed"
  type = object({
    name      = string
    port      = number
    log_level = optional(string, "info")
  })
  default = {
    name = "checkout"
    port = 8080
  }
}
 
variable "upstream_hosts" {
  description = "Private IPs of the app servers"
  type        = list(string)
  default     = ["10.0.1.10", "10.0.1.11"]
}
 
variable "extra_labels" {
  description = "Labels merged into every generated file"
  type        = map(string)
  default     = {}
}
 
variable "log_retention_days" {
  description = "Days to keep application logs"
  type        = number
  default     = 14
  nullable    = false
}
 
variable "db_password" {
  description = "Password the service uses to reach its database"
  type        = string
  sensitive   = true
}
ArgumentWhat it does
typeType constraint. Values are converted to it or rejected.
defaultUsed when nothing else sets a value. No default means the variable is required.
descriptionShown in prompts and generated docs. Write one; future you will read it.
validationRules the value must pass, with your own error message.
sensitiveHides the value in plan and apply output.
nullablefalse means an explicit null falls back to the default.

You refer to a variable anywhere in the configuration as var.NAME, for example var.replicas or var.service.port.

Types

Always give variables a type. Without one, Terraform accepts anything, and a bad value fails later, deep inside some expression, instead of at the boundary where it came in.

TypeExample valueNotes
string"checkout"
number8080, 0.5One numeric type for integers and decimals.
booltrue
list(string)["10.0.1.10", "10.0.1.11"]Ordered; duplicates allowed.
set(string)toset(["a", "b"])Unordered; duplicates removed.
map(string){ team = "payments" }String keys; every value has the same type.
object(...){ name = "checkout", port = 8080 }Fixed attribute names, each with its own type.
tuple(...)["web", 443]Fixed length; a type per position.
anyTerraform infers the type. Avoid it for inputs.

object is the one beginners under-use. The service variable groups three related settings, and optional(string, "info") makes log_level optional with a default, so callers pass only what they need to change.

Supplying values

The project needs one provider, so run terraform init first; it installed hashicorp/local v2.9.1 for me. db_password has no default, so it's required. In a terminal Terraform would stop and prompt for it. CI pipelines pass -input=false, which turns the prompt into an error:

terraform plan -input=false
╷
│ Error: No value for required variable
│ 
│   on variables.tf line 55:
│   55: variable "db_password" {
│ 
│ The root module input variable "db_password" is not set, and has no default
│ value. Use a -var or -var-file command line argument to provide a value for
│ this variable.
╵

For a secret, the right channel is an environment variable named TF_VAR_ plus the variable name. Your CI system injects it from its secret store, and it never lands in a file in the repository:

export TF_VAR_db_password='s3cr3t-Pa55'
terraform plan
[…]
  # local_file.settings will be created
  + resource "local_file" "settings" {
      + content              = jsonencode(
            {
              + labels             = {
                  + environment = "dev"
                  + managed_by  = "terraform"
                  + service     = "checkout"
                }
              + log_level          = "info"
              + log_retention_days = 14
              + port               = 8080
              + replicas           = 2
              + service            = "checkout"
            }
        )
[…]
  # local_sensitive_file.db_env will be created
  + resource "local_sensitive_file" "db_env" {
      + content              = (sensitive value)
[…]
Plan: 3 to add, 0 to change, 0 to destroy.
 
Changes to Outputs:
  + db_url           = (sensitive value)
  + settings_file    = "./out/checkout-dev.json"
  + upstream_servers = [
      + "10.0.1.10:8080",
      + "10.0.1.11:8080",
    ]

Terraform pretty-printed the jsonencode(...) content as a structure, so a reviewer can read the settings, and the password shows only as (sensitive value). Apply it and look at what was generated:

terraform apply -auto-approve
ls -l out
jq . out/checkout-dev.json
cat out/checkout-dev-upstream.conf
[…]
Apply complete! Resources: 3 added, 0 changed, 0 destroyed.
[…]
total 12
-rw------- 1 sid sid  24 Nov  9 21:39 checkout-dev-db.env
-rw-r--r-- 1 sid sid 144 Nov  9 21:39 checkout-dev-upstream.conf
-rw-r--r-- 1 sid sid 167 Nov  9 21:39 checkout-dev.json
{
  "labels": {
    "environment": "dev",
    "managed_by": "terraform",
    "service": "checkout"
  },
  "log_level": "info",
  "log_retention_days": 14,
  "port": 8080,
  "replicas": 2,
  "service": "checkout"
}
# Generated by Terraform for checkout-dev. Do not edit by hand.
upstream checkout-dev {
    server 10.0.1.10:8080;
    server 10.0.1.11:8080;
}

The secrets file got mode 0600 because its resource said so. Keep that pattern in mind: wherever a sensitive value ends up, protect it at the destination too.

Type conversion and type errors

Terraform converts values to the declared type when it can and refuses when it can't. Command-line values always arrive as strings, so -var 'replicas=3' works because "3" converts cleanly to a number. three doesn't:

terraform plan -input=false -var 'replicas=three'
[…]
╷
│ Error: Invalid value for input variable
│ 
│   on variables.tf line 12:
│   12: variable "replicas" {
│ 
│ Unsuitable value for var.replicas set using -var="replicas=...": a number
│ is required.
╵

Objects are checked attribute by attribute. Leaving out port fails with attribute "port" is required. Leaving out an optional attribute fills in its default, which you can check with terraform console, an interactive prompt that evaluates expressions against your configuration. You can also pipe a single expression into it:

echo 'var.service' | terraform console -var 'service={name="cart", port=9090}'
{
  "log_level" = "info"
  "name" = "cart"
  "port" = 9090
}

We'll lean on the console for the rest of the tutorial. It's the fastest way to answer "what does this evaluate to?"

Validation rules

Types catch "this is not a number". Validation catches "this number makes no sense here". Each validation block has a condition that must be true and an error_message for when it isn't:

terraform plan -input=false -var 'environment=production'
Planning failed. Terraform encountered an error while generating this plan.
 
╷
│ Error: Invalid value for variable
│ 
│   on variables.tf line 1:
│    1: variable "environment" {
│     ├────────────────
│     │ var.environment is "production"
│ 
│ environment must be one of: dev, staging, prod.
│ 
│ This was checked by the validation rule at variables.tf:6,3-13.
╵

The message shows the offending value and points at the exact rule. -var 'replicas=0' fails the same way with replicas must be between 1 and 10. A variable can have several validation blocks, each reported separately. Write messages that say what is allowed, not just that something is wrong.

Sensitive and nullable

sensitive = true redacts a value wherever Terraform would print it, including the console:

echo 'var.db_password' | terraform console
(sensitive value)

Two caveats. First, sensitivity is about display: the value is still stored in plain text in the state file, which is one reason state needs protecting (see Terraform State). Second, sensitivity is contagious: anything computed from a sensitive value is sensitive too. That's why db_url in outputs.tf has to be marked sensitive; you'll see the error you get without it in Common mistakes.

nullable = false controls what an explicit null means. By default null is a legal value that replaces the default. With nullable = false, null means "use the default". I put log_retention_days = null in retention.tfvars:

echo 'var.log_retention_days' | terraform console -var-file=retention.tfvars
14

When I flipped the variable to nullable = true, the same command printed tonumber(null), the console's way of showing a null number. Nulls usually arrive from modules that pass optional inputs straight through, so nullable = false is a cheap guarantee for any variable your configuration can't work without.

Where values come from, and which one wins

When several sources set the same variable, the later one in this table wins:

PrecedenceSourceTypical use
1 (lowest)default in the variable blockA sensible baseline
2TF_VAR_name environment variableSecrets and CI settings
3terraform.tfvars (or terraform.tfvars.json)Per-directory values, loaded automatically
4*.auto.tfvars files, in alphabetical orderExtra auto-loaded overrides
5 (highest)-var and -var-file, in command-line orderPer-run and per-environment values

Don't take a table's word for it. Here is every layer stacked onto replicas, one at a time:

echo 'var.replicas' | terraform console
export TF_VAR_replicas=3
echo 'var.replicas' | terraform console
echo 'replicas = 4' > terraform.tfvars
echo 'var.replicas' | terraform console
echo 'replicas = 5' > ha.auto.tfvars
echo 'var.replicas' | terraform console
echo 'replicas = 6' > load-test.tfvars
echo 'var.replicas' | terraform console -var-file=load-test.tfvars
echo 'var.replicas' | terraform console -var-file=load-test.tfvars -var 'replicas=7'
echo 'var.replicas' | terraform console -var 'replicas=7' -var-file=load-test.tfvars
2
3
4
5
6
7
6

Each layer overrode the one before. The last two lines are the subtle part: -var and -var-file have equal rank, and whichever comes last on the command line wins. Auto-loaded files go in filename order, so when I added zz-override.auto.tfvars containing replicas = 8, a plain echo 'var.replicas' | terraform console printed 8: it beat ha.auto.tfvars.

My advice: default for safe baselines, -var-file=envs/NAME.tfvars for environment differences, TF_VAR_ for secrets, and -var only for one-off experiments. Avoid *.auto.tfvars in shared repositories. Values that load themselves without appearing on the command line are exactly the ones that surprise a teammate.

Local values

A locals block names an expression so you can reuse it. These are the locals in main.tf:

locals {
  name_prefix = "${var.service.name}-${var.environment}"
  is_prod     = var.environment == "prod"
 
  labels = merge(
    {
      service     = var.service.name
      environment = var.environment
      managed_by  = "terraform"
    },
    var.extra_labels,
  )
 
  settings = {
    service            = var.service.name
    port               = var.service.port
    log_level          = local.is_prod ? "warn" : var.service.log_level
    replicas           = var.replicas
    log_retention_days = var.log_retention_days
    labels             = local.labels
  }
}

You refer to them as local.NAME (singular, though the block is locals). The difference from a variable is who controls the value: a variable is an input the caller sets; a local is an internal value computed from inputs. Nobody can override local.is_prod from the command line, and that's the point. If production always logs at warn, encode the rule once in a local instead of trusting every caller to pass the right log level.

The rest of main.tf declares the provider and the three resources that consume the locals:

terraform {
  required_version = ">= 1.5"
 
  required_providers {
    local = {
      source  = "hashicorp/local"
      version = "~> 2.5"
    }
  }
}
 
resource "local_file" "settings" {
  filename        = "${path.module}/out/${local.name_prefix}.json"
  content         = jsonencode(local.settings)
  file_permission = "0644"
}
 
resource "local_file" "upstream" {
  filename        = "${path.module}/out/${local.name_prefix}-upstream.conf"
  file_permission = "0644"
  content = templatefile("${path.module}/templates/upstream.conf.tftpl", {
    name  = local.name_prefix
    port  = var.service.port
    hosts = var.upstream_hosts
  })
}
 
resource "local_sensitive_file" "db_env" {
  filename        = "${path.module}/out/${local.name_prefix}-db.env"
  content         = "DB_PASSWORD=${var.db_password}\n"
  file_permission = "0600"
}

A rule of thumb: if an expression appears twice, or needs a name to be understood, make it a local. If a local is used once and its name says nothing the expression doesn't, inline it.

Outputs

Outputs are a configuration's return values. They're printed after apply, readable any time with terraform output, and (once you write modules) they're how one module hands values to another. Here is outputs.tf:

output "settings_file" {
  description = "Path of the generated settings file"
  value       = local_file.settings.filename
}
 
output "upstream_servers" {
  description = "host:port pairs the load balancer will use"
  value       = [for host in var.upstream_hosts : "${host}:${var.service.port}"]
}
 
output "db_url" {
  description = "Connection string for the service"
  value       = "postgres://${var.service.name}:${var.db_password}@db.internal:5432/${var.service.name}"
  sensitive   = true
}

terraform output with no arguments redacts sensitive outputs. Asking for one by name does not:

terraform output
terraform output db_url
terraform output -raw settings_file
db_url = <sensitive>
settings_file = "./out/checkout-dev.json"
upstream_servers = [
  "10.0.1.10:8080",
  "10.0.1.11:8080",
]
"postgres://checkout:s3cr3t-Pa55@db.internal:5432/checkout"
./out/checkout-dev.json

-raw prints a plain string without quotes, for shell scripts. -json prints outputs with their types, and it prints sensitive values in full:

terraform output -json | jq '.db_url'
{
  "sensitive": true,
  "type": "string",
  "value": "postgres://checkout:s3cr3t-Pa55@db.internal:5432/checkout"
}

So sensitive protects you from accidental display, not from anyone who asks for the value. Never send terraform output -json to a log you don't control. It is still the right way for scripts to read outputs:

terraform output -json upstream_servers | jq -r '.[]'
10.0.1.10:8080
10.0.1.11:8080

Expressions

Everything to the right of an = is an expression. These are the forms you'll use daily, evaluated in terraform console against our project:

terraform console
> "${var.service.name}-${var.environment}"
"checkout-dev"
> local.is_prod ? 3 : 1
1
> [for h in var.upstream_hosts : "${h}:${var.service.port}"]
[
  "10.0.1.10:8080",
  "10.0.1.11:8080",
]
> { for h in var.upstream_hosts : h => var.service.port }
{
  "10.0.1.10" = 8080
  "10.0.1.11" = 8080
}
> [for h in var.upstream_hosts : h if h != "10.0.1.11"]
[
  "10.0.1.10",
]
> { for k, v in local.labels : upper(k) => v }
{
  "ENVIRONMENT" = "dev"
  "MANAGED_BY" = "terraform"
  "SERVICE" = "checkout"
}
> [{ name = "web", port = 443 }, { name = "metrics", port = 9100 }][*].port
[
  443,
  9100,
]
  • Interpolation: ${…} inside a double-quoted string inserts a value. A bare reference such as var.replicas needs no quotes; wrapping it as "${var.replicas}" just to pass it along is an old habit you can drop.
  • Conditional: condition ? if_true : if_false. Keep both branches the same type.
  • for expressions: square brackets build a list, curly braces build a map (with key => value). A trailing if filters. Iterating a map gives you key and value.
  • Splat: list[*].attr is shorthand for [for x in list : x.attr]. You'll use it most with resources created by count, in count, for_each, and Dynamic Blocks.

Template files add directives. In templates/upstream.conf.tftpl, %{ for … } repeats a line per host, and ~ strips the adjacent newline so the loop leaves no blank lines:

# Generated by Terraform for ${name}. Do not edit by hand.
upstream ${name} {
%{ for host in hosts ~}
    server ${host}:${port};
%{ endfor ~}
}

Built-in functions

Terraform has no user-defined functions, but it ships with over a hundred built-in ones, so it pays to know the common ones:

> format("%s-%03d", local.name_prefix, 7)
"checkout-dev-007"
> join(", ", var.upstream_hosts)
"10.0.1.10, 10.0.1.11"
> lookup({ dev = "t3.micro", prod = "m6i.large" }, var.environment, "t3.small")
"t3.micro"
> merge(local.labels, { owner = "payments-team" })
{
  "environment" = "dev"
  "managed_by" = "terraform"
  "owner" = "payments-team"
  "service" = "checkout"
}
> coalesce("", var.service.log_level)
"info"
> var.extra_labels["team"]
╷
│ Error: Invalid index
│ 
│   on <console-input> line 1:
│   (source code not available)
│ 
│ The given key does not identify an element in this collection value.
╵
 
> try(var.extra_labels["team"], "unassigned")
"unassigned"
> cidrsubnet("10.20.0.0/16", 8, 3)
"10.20.3.0/24"
> jsonencode({ port = var.service.port, hosts = var.upstream_hosts })
"{\"hosts\":[\"10.0.1.10\",\"10.0.1.11\"],\"port\":8080}"
FunctionWhat it's for
formatprintf-style formatting, such as zero-padded names like web-007.
join / splitList to string and back.
lookupMap lookup with a fallback for a missing key.
mergeCombine maps; later maps win on duplicate keys. The standard way to layer default labels with caller-supplied ones.
coalesceFirst argument that isn't null or an empty string.
tryFirst expression that evaluates without an error. The safe way to read optional keys, as the Invalid index error shows.
cidrsubnetCarve subnets out of a network range: the core of most VPC layouts.
jsonencode / jsondecodeConvert between Terraform values and JSON text. Never hand-write JSON in a heredoc.
fileA file's contents as a string, unprocessed.
templatefileA file rendered as a template with the variables you pass.

templatefile is how local_file.upstream got its content. You can render the same template with different values in the console:

> templatefile("${path.module}/templates/upstream.conf.tftpl", { name = "cart-dev", port = 9090, hosts = ["10.0.3.5"] })
<<EOT
# Generated by Terraform for cart-dev. Do not edit by hand.
upstream cart-dev {
    server 10.0.3.5:9090;
}
 
EOT

path.module is the directory of the current module, which keeps file paths working no matter where Terraform runs from. Keep templates in .tftpl files rather than inline heredocs; editors highlight them and diffs stay readable.

Where you'll use this

The most common real-world use of all of the above is one configuration, one variables file per environment:

tree envs
envs
├── dev.tfvars
└── prod.tfvars

envs/prod.tfvars holds only what differs from the defaults:

environment = "prod"
replicas    = 4
 
upstream_hosts = [
  "10.0.1.10",
  "10.0.1.11",
  "10.0.2.10",
  "10.0.2.11",
]
 
extra_labels = {
  team    = "payments"
  oncall  = "payments-primary"
  backups = "daily"
}
 
log_retention_days = 90

The production CI job runs terraform plan -var-file=envs/prod.tfvars with TF_VAR_db_password injected from the CI secret store. Here's what that plan showed when I ran it in the directory that already held the dev deployment:

terraform plan -var-file=envs/prod.tfvars
[…]
  # local_file.settings must be replaced
-/+ resource "local_file" "settings" {
      ~ content              = jsonencode(
          ~ {
              ~ labels             = {
                  + backups     = "daily"
                  ~ environment = "dev" -> "prod"
                  + oncall      = "payments-primary"
                  + team        = "payments"
                    # (2 unchanged attributes hidden)
                }
              ~ log_level          = "info" -> "warn"
              ~ log_retention_days = 14 -> 90
              ~ replicas           = 2 -> 4
                # (2 unchanged attributes hidden)
            } # forces replacement
        )
[…]
      ~ filename             = "./out/checkout-dev.json" -> "./out/checkout-prod.json" # forces replacement
[…]
Plan: 3 to add, 0 to change, 3 to destroy.

Two lessons are in that output. The good one: the diff reads like a change request. log_level became warn because of the is_prod local, not because anyone remembered to set it, and every prod-only label is visible for review. The bad one is 3 to destroy: both environments share one state file, so Terraform plans to replace the dev files with prod ones. With cloud resources, that means tearing down dev to build prod. Variables give each environment its own values; each also needs its own state, which is what Managing Multiple Environments sets up. I did not apply this plan.

You'll reach for the same tools for:

  • Feature flags for infrastructure: a bool variable such as enable_backups plus a conditional switches optional resources per environment (the pattern is in count, for_each, and Dynamic Blocks).
  • Consistent tagging: merge(local.default_tags, var.extra_tags) is how most teams make sure every cloud resource carries owner and cost-centre labels.
  • Feeding other tools: CI jobs read terraform output -json to find the URL to smoke-test or the hosts to deploy to.

Common mistakes

"Output refers to sensitive values"

I added a quick debugging output that exposed the password variable:

output "db_password_debug" {
  value = var.db_password
}
╷
│ Error: Output refers to sensitive values
│ 
│   on debug.tf line 1:
│    1: output "db_password_debug" {
│ 
│ To reduce the risk of accidentally exporting sensitive data that was
│ intended to be only internal, Terraform requires that any root module
│ output containing sensitive data be explicitly marked as sensitive, to
│ confirm your intent.
│ 
│ If you do intend to export this data, annotate the output value as
│ sensitive by adding the following argument:
│     sensitive = true
╵

The fix is in the message: add sensitive = true. The same error appears for outputs that merely derive from a sensitive value, like db_url. If you're tempted to wrap the value in nonsensitive() to silence it, first ask whether it should be an output at all.

"Variables not allowed"

Some blocks are read before variables exist. The backend block is the classic case:

variable "state_path" {
  type    = string
  default = "state/app.tfstate"
}
 
terraform {
  backend "local" {
    path = var.state_path
  }
}
terraform init
Initializing the backend...
 
╷
│ Error: Variables not allowed
│ 
│   on main.tf line 8, in terraform:
│    8:     path = var.state_path
│ 
│ Variables may not be used here.
╵

The same restriction applies to required_version and required_providers. For backends, use partial configuration (terraform init -backend-config=...), covered in Terraform State.

"Invalid escape sequence" in a regex

HCL strings treat a backslash as an escape character, so a regular expression pasted from another language breaks:

condition = can(regex("^\d+(\.\d+){3}$", var.hostname_pattern_demo))
╷
│ Error: Invalid escape sequence
│ 
│   on main.tf line 6, in variable "hostname_pattern_demo":
│    6:     condition     = can(regex("^\d+(\.\d+){3}$", var.hostname_pattern_demo))
│ 
│ The symbol "d" is not a valid escape sequence selector.
╵

Double every backslash: "^\\d+(\\.\\d+){3}$". With that change validate passed, and the rule rejected web-1 as intended.

A related typo, var.service.loglevel instead of log_level, is caught by terraform validate as Unsupported attribute ... This object does not have an attribute named "loglevel". That early catch is one more argument for typed object variables over any.

Summary

  • Declare every input with a type and a description; leave out default only for values that must be supplied, and mark secrets sensitive = true.
  • validation blocks reject bad values at plan time, before any resource is touched; write error messages that say what is allowed.
  • object types with optional(type, default) attributes group related settings and let callers pass only what they change.
  • Precedence, lowest to highest: default, TF_VAR_name, terraform.tfvars, *.auto.tfvars (alphabetical), then -var and -var-file in command-line order.
  • Locals are internal named expressions that callers can't override; use them to encode rules like "prod logs at warn".
  • sensitive hides values from display only: they're still in state, returned by terraform output NAME, and printed in full by terraform output -json.
  • for expressions, splats, conditionals and functions such as merge, try, templatefile and jsonencode cover nearly all day-to-day data shaping; try them in terraform console before putting them in a file.

Exercises

These build on the checkout project. Keep TF_VAR_db_password exported while you work.

Exercise 1: Predict the winnereasy

Set TF_VAR_replicas=9 in your shell and put replicas = 3 in terraform.tfvars. Predict what var.replicas evaluates to, then predict it again with -var 'replicas=5' added. Check both answers with terraform console.

Show Solution
export TF_VAR_replicas=9
echo 'replicas = 3' > terraform.tfvars
echo 'var.replicas' | terraform console
echo 'var.replicas' | terraform console -var 'replicas=5'
3
5

terraform.tfvars outranks environment variables, and command-line flags outrank both. Clean up with unset TF_VAR_replicas and rm terraform.tfvars so they don't leak into the next exercise.

Exercise 2: Validate the log levelmedium

service.log_level accepts any string today. Add a rule to the service variable that allows only debug, info, warn and error, and prove it rejects verbose.

Hint

A validation condition can reach into the object: var.service.log_level. contains(list, value) returns a bool.

Show Solution

Add this inside variable "service", after the default:

  validation {
    condition     = contains(["debug", "info", "warn", "error"], var.service.log_level)
    error_message = "service.log_level must be debug, info, warn or error."
  }
terraform plan -input=false -var 'service={name="checkout", port=8080, log_level="verbose"}'
Planning failed. Terraform encountered an error while generating this plan.
 
╷
│ Error: Invalid value for variable
│ 
│   on variables.tf line 23:
│   23: variable "service" {
│     ├────────────────
│     │ var.service.log_level is "verbose"
│ 
│ service.log_level must be debug, info, warn or error.
│ 
│ This was checked by the validation rule at variables.tf:35,3-13.
╵

The rule sees the value after the optional default is applied, so callers who omit log_level still pass with "info".

Exercise 3: Reject anything that isn't an IPv4 addresshard

Add two rules to upstream_hosts: the list must not be empty, and every entry must be a valid IPv4 address. Test with [], with ["10.0.1.10", "app-2.internal"], and with a valid list.

Hint

alltrue() takes a list of bools, which a for expression can build. can() returns false instead of failing when an expression errors, and cidrhost() errors on anything that isn't a valid address.

Show Solution
variable "upstream_hosts" {
  description = "Private IPs of the app servers"
  type        = list(string)
  default     = ["10.0.1.10", "10.0.1.11"]
 
  validation {
    condition     = length(var.upstream_hosts) > 0
    error_message = "At least one upstream host is required."
  }
 
  validation {
    condition     = alltrue([for h in var.upstream_hosts : can(cidrhost("${h}/32", 0))])
    error_message = "Every upstream host must be an IPv4 address such as 10.0.1.10."
  }
}
terraform plan -input=false -var 'upstream_hosts=[]'
terraform plan -input=false -var 'upstream_hosts=["10.0.1.10","app-2.internal"]'
terraform plan -input=false -var 'upstream_hosts=["10.0.1.10","10.0.1.12"]'
[…]
│     │ var.upstream_hosts is empty list of string
│ 
│ At least one upstream host is required.
[…]
│     │ var.upstream_hosts is list of string with 2 elements
│ 
│ Every upstream host must be an IPv4 address such as 10.0.1.10.
[…]
                server 10.0.1.10:8080;
          -     server 10.0.1.11:8080;
          +     server 10.0.1.12:8080;
[…]
Plan: 1 to add, 0 to change, 1 to destroy.

cidrhost is a sturdier validator than a regex. In the console, can(regex("^\\d{1,3}(\\.\\d{1,3}){3}$", "999.1.1.1")) returned true, while can(cidrhost("999.1.1.1/32", 0)) returned false.

Exercise 4: A staging environment and a map outputmedium

Create staging.tfvars that sets environment = "staging", replicas = 3 and a team = "payments" label. Add an output upstream_by_host that maps each upstream host to its host:port string. Apply with the new file, then use jq to print each pair as host -> address.

Show Solution
# staging.tfvars
environment = "staging"
replicas    = 3
 
extra_labels = {
  team = "payments"
}
# added to outputs.tf
output "upstream_by_host" {
  description = "Map of upstream host to its host:port address"
  value       = { for host in var.upstream_hosts : host => "${host}:${var.service.port}" }
}
terraform apply -auto-approve -var-file=staging.tfvars
terraform output -json upstream_by_host | jq -r 'to_entries[] | "\(.key) -> \(.value)"'
jq -c . out/checkout-staging.json
[…]
Apply complete! Resources: 3 added, 0 changed, 3 destroyed.
 
Outputs:
 
db_url = <sensitive>
settings_file = "./out/checkout-staging.json"
upstream_by_host = {
  "10.0.1.10" = "10.0.1.10:8080"
  "10.0.1.11" = "10.0.1.11:8080"
}
[…]
10.0.1.10 -> 10.0.1.10:8080
10.0.1.11 -> 10.0.1.11:8080
{"labels":{"environment":"staging","managed_by":"terraform","service":"checkout","team":"payments"},"log_level":"info","log_retention_days":14,"port":8080,"replicas":3,"service":"checkout"}

Note 3 destroyed: the dev files were replaced by staging ones, which is the shared-state problem from Where you'll use this in action.


Tested with: Terraform v1.17.1 and the hashicorp/local provider v2.9.1 on Ubuntu 24.04 (WSL2, linux_amd64), November 2026. Every configuration was applied and every output comes from a real run, trimmed where marked […]. Console sessions were run by piping one expression at a time into terraform console and are shown in the format the interactive prompt prints. I ran the production plan but deliberately did not apply it.

Was this page helpful?
The Dark Debugger

Written by The Dark Debugger

Engineer documenting the things that took me too long to learn, so they take you less time. Every Terraform tutorial here is tested end to end before publishing.