Back to Terraform

Variables, Locals and Outputs as a Typed Interface

November 5, 2026 Wasil Zafar 32 min read

Design configuration inputs and outputs with precise types, defaults and validation

Table of Contents

  1. Choose Types That Describe the Actual Contract
  2. Distinguish Missing, Null, Empty and Unknown Values
  3. Trace Where a Root Variable Gets Its Value
  4. Use Locals to Name Decisions Without Hiding Inputs
  5. Outputs Are an API with Exposure Consequences
  6. Reject Bad Inputs with an Actionable Message

Choose Types That Describe the Actual Contract

A module that takes no input is a script. A module that takes any is a script with a suggestion box. The difference between a reusable module and a fragile one is usually not the resources inside it but the shape of the values going in and coming out.

Think of a variable block as a function signature written for someone who will never read the body. Type states what the caller must supply; default states what happens when they say nothing; validation states the rules a type alone cannot express. Get those three right and most misuse is caught before Terraform talks to a provider.

The running example for this article is one small service:

variable "service" {
  type = object({
    name     = string
    replicas = number
    ports    = list(number)
    tags     = map(string)
  })
}

That is already a contract: four attributes, all required, each with a type. A caller cannot send a singular port where the contract expects ports, send text where a number belongs, or leave tags out. Terraform reports the mismatch against the block that declared it rather than deep inside a provider call.

Primitive types describe one value. String is text, number is a decimal number, and bool is exactly true or false.

Two details surprise beginners. Number is not an integer type, so a fraction such as 1.5 is valid and replicas needs a whole-number rule if fractions are meaningless. Terraform converts between types when a conversion is defined: the string "3" becomes the number 3 for a number variable, and a number becomes text for a string variable. A conversion is not a validation: it succeeds quietly, which is why "yes" is not a bool, a quoted number may be intentional, and neither case tells you whether the value makes sense.

A conversion is not a validation

Terraform turns "3" into the number 3 for a number variable and silently discards object attributes the type does not declare. The type narrows the shape; it does not judge whether the value makes sense. Put that judgment in a validation block, where it can explain itself.

Collection types describe many values of one element type. A list is ordered and indexable, and duplicates are allowed. A set is unordered, has no index, and holds each distinct value once; it is the right type for a set of allowed ports and the wrong type for a list of listeners whose first entry is the default. A map has string keys and uniformly typed values, which suits labels, annotations and environment maps. Converting a list to a set silently drops duplicates and ordering, so a conversion can destroy information the caller cared about.

Structural types describe shape. An object has named attributes, each with its own type, and is the natural fit for a service record. A tuple has a fixed number of positions with a possibly different type at each, and it is the right choice only when position itself is the contract, such as an address-and-port pair.

A tuple of the wrong length fails; an object with an extra attribute does not. Terraform converts a map or object to the declared object type and discards attributes the schema does not mention. That discard is convenient and dangerous: a caller who misspells a required attribute gets an error because the attribute is missing, but a caller who adds a region attribute watches it disappear. If an attribute matters, declare it.

Optional attributes refine an object. image = optional(string, "ghcr.io/example/api:1.4.0") means the caller may omit the attribute and conversion fills the default. Without a second argument, an omitted optional attribute becomes null, which the body must then handle. Optional attributes require Terraform 1.3 or later, well below the pinned CLI in this series.

Figure 1 is the decision path: count the values, then decide whether order, uniqueness or names are part of the contract. Figure 2 shows the same decision as layers inside one interface, and Table 1 states what each constraint does and does not catch.

Choose Types That Describe the Actual Contract
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    A["Value arrives from a caller"] --> B{"How many values?"}
    B -->|"one"| C{"What kind of single value?"}
    C -->|"text"| C1["string"]
    C -->|"quantity"| C2["number"]
    C -->|"on or off"| C3["bool"]
    B -->|"many, one element type"| D{"Are order and uniqueness part of the meaning?"}
    D -->|"ordered, duplicates allowed"| D1["list(T)"]
    D -->|"unordered, unique"| D2["set(T)"]
    D -->|"named keys, uniform values"| D3["map(T)"]
    B -->|"fixed shape"| E{"Named attributes or fixed positions?"}
    E -->|"positions, fixed count"| E1["tuple([T1, T2])"]
    E -->|"named attributes"| E2["object with named attributes"]
    E2 --> F["optional(T, default) for a safe omission"]
    F --> G["Required attribute stays required"]
    classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
    classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
    classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
    classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
    classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
    class A primary;
    class B,C,D,E secondary;
    class C1,C2,C3,D1,D2,D3,E1,E2 ok;
    class F warn;
    class G primary;
Three layers of one type constraint A dashed interface boundary holds a structural band naming the object attributes, a collection band describing the ports list and tags map, and a primitive band describing one string, number or boolean. An amber note marks an optional attribute with a default. One interface, three layers of meaning variable "service" boundary structural: which attributes exist name = string replicas = number ports = list(number) tags = map(string) extra attributes are discarded on conversion collection: how many and in what order list keeps order and duplicates set is unique and unordered, map is keyed by name primitive: what one value is string, number, bool, each with defined conversions optional(string, default) omitted attribute is filled without a default it is null conversion is not validation "3" converts to 3, "" stays a valid empty string A precise type narrows the value; it does not judge whether the value is sensible.
Type constraintContract it statesConversions acceptedStill passes without an errorReach for it when
stringOne text valuenumber and bool convert to text; "true" and "false" convert back to boolAn empty string, or any spelling you did not rule outNames, image references, messages, formatted identifiers
numberOne decimal number, not necessarily wholeNumeric strings such as "3" convert; a bool never does0, negative values and fractionsCounts, sizes and thresholds that need range and whole-number rules
boolExactly true or falseThe strings "true" and "false" convertNothing else: yes, no, 1 and 0 are rejectedFeature switches and binary decisions
list(T)Ordered sequence, duplicates allowed, indexabletuple and set convert; a set loses its orderAn empty list, and any element value the element type allowsPositional data where the first item has meaning
set(T)Unordered, unique elements, no indexlist and tuple convert, silently dropping duplicates and orderAn empty set, and order-dependent input that is quietly reorderedMembership tests, allowed-value checks, for_each keys
map(T)String keys and uniformly typed valuesAn object with uniform attribute types convertsAn empty map; a missing key fails later, on accessLabels, annotations, environment maps, small lookups
object({ ... })Specific attribute names, each with its own typemap or a wider object converts; extra attributes are discardedA valid object whose values are still nonsensicalA stable record such as the service object
tuple([ ... ])Fixed positions, fixed length, per-position typesA list converts when every position matchesNothing structural; a wrong length or type is rejectedPairs and triples where position is the contract
optional(T, default)An object attribute that may be omittedThe omitted attribute receives the default during conversionAn explicit null, unless nullable = false blocks itAttributes with a safe default that most callers want

Distinguish Missing, Null, Empty and Unknown Values

Four different things get called "no value", and Terraform treats them differently. Confusing them produces modules that either reject a good call or accept a bad one.

Missing means the caller supplied nothing for the variable. If the block has no default, the variable is required: the CLI prompts for it interactively, and a run with -input=false fails instead of waiting. If the block has a default, the default is used. Missing is a property of the assignment, not a value that reaches your expressions.

Null is an explicit value meaning "no value here". A caller can write replicas = null or pass a null from a parent module. Nullable defaults to true, so a null is accepted and lands in the replicas attribute as null; any arithmetic on it then fails with an error about the argument, often far from the call site. Setting nullable to false makes a null variable an error, which is usually what a required attribute wants. Nullability is shallow: a non-null object may still contain a null attribute, and an optional attribute without a default is exactly that.

Empty is a real value: an empty string, list or map. It has a type, it satisfies the type constraint, and its length is zero. This is why a non-null setting does not protect you from a service with no ports. An empty value is a decision the caller made, and the only way to reject it is a rule that names it.

Unknown means Terraform cannot know the value yet. A provider-computed attribute, such as an allocated address, is unknown at plan time and prints as (known after apply). Unknown is not empty and not invalid. It is also contagious: a comparison involving an unknown value is itself unknown, so a condition cannot be evaluated as true or false. Terraform defers the check until the value exists, or rejects the operation when it needs the value early. Count and for_each cannot use unknown values, and a validation that depends on one cannot decide at plan time. A plan that passes is not proof every rule will pass at apply; it is proof no rule has failed yet.

Figure 3 follows the decision order Terraform applies to an incoming value, with the failure branches where a rule or a null stops the run.

Distinguish Missing, Null, Empty and Unknown Values
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    A["variable block: type, default, nullable, validation"] --> B{"Value supplied by the caller?"}
    B -->|"no"| C{"default declared?"}
    C -->|"no"| C1["Required: prompt, or fail with -input=false"]
    C -->|"yes"| D["Default value is used"]
    B -->|"yes"| E{"Explicitly null?"}
    E -->|"yes"| F{"nullable = false?"}
    F -->|"yes"| F1["Error: required variable is null"]
    F -->|"no"| G["null reaches expressions"]
    E -->|"no"| H{"Empty string, empty list or empty map?"}
    H -->|"yes"| H1["Valid value: length rules must reject it"]
    H -->|"no"| I{"Known before apply?"}
    I -->|"no"| I1["Unknown: rule is deferred, plan shows known after apply"]
    I -->|"yes"| J{"Type and validation satisfied?"}
    J -->|"no"| J1["Error before the plan proceeds"]
    J -->|"yes"| K["Known, typed, valid value"]
    classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
    classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
    classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
    classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
    classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
    class A,K primary;
    class B,C,E,F,H,I,J secondary;
    class C1,F1,J1 danger;
    class D,G,H1,I1 warn;
StateWhat it meansTypical mistakeGuard
MissingThe caller supplied nothingAssuming a required variable has a defaultDeclare a default, or accept the prompt/failure
NullAn explicit "no value"Arithmetic on a null attributenullable = false, or handle null in the body
EmptyA real "", [] or {}Treating empty as absentA validation rule that checks length()
UnknownNot knowable until applyValidating a value that does not exist yetA check block or a precondition that runs later

The practical rule: use nullable = false to stop a whole variable being null, validation to stop empty and out-of-range values, and a check block or precondition for anything that depends on an apply-time value.

Trace Where a Root Variable Gets Its Value

Only root module variables are assignable from outside. A child module gets its values as arguments in a module block, and nothing else can set them. So "where did this value come from" is a root-module question, and the answer is a fixed order of sources.

Terraform loads root variable values in this sequence, and each later source overrides an earlier one for the same variable:

  1. The default argument in the variable block. This is the weakest source.
  2. Environment variables named TF_VAR_<name>, for example TF_VAR_service for variable "service".
  3. A file named exactly terraform.tfvars in the working directory.
  4. A file named exactly terraform.tfvars.json.
  5. Every *.auto.tfvars and *.auto.tfvars.json file, in lexical order by filename, so 10-network.auto.tfvars is applied before 20-app.auto.tfvars.
  6. -var and -var-file options on the command line, applied in the order they appear. When the run executes in HCP Terraform, workspace and variable-set values sit at this top tier as well.
variable "service" {
  type = object({
    name     = string
    replicas = number
    ports    = list(number)
    tags     = map(string)
  })
}

# terraform.tfvars
service = {
  name     = "api"
  replicas = 2
  ports    = [8080]
  tags     = { env = "dev" }
}
export TF_VAR_service='{"name":"api","replicas":4,"ports":[8080],"tags":{"env":"dev"}}'
terraform plan
terraform plan -var='service={"name":"api","replicas":8,"ports":[8080],"tags":{"env":"dev"}}'

The order is not the order you might guess. Environment variables are loaded early, so a checked-in terraform.tfvars overrides TF_VAR_service. That is deliberate for CI: a pipeline can inject a baseline through the environment, while the repository's tfvars still expresses the team's decision. It also surprises people who expect the shell to win.

Precedence replaces, it does not merge

Precedence is per variable, not per attribute. If an environment variable sets the whole object and a tfvars file also sets the whole object, the higher source replaces the object; the attributes are not merged. That is why a partial object in an environment variable usually fails the required-attribute check rather than patching one field.

The tfvars syntax follows from the same design: assignments, not declarations.

# terraform.tfvars: assignment only, no blocks
replicas = 3
tags     = { env = "dev" }
{
  "replicas": 3,
  "tags": { "env": "dev" }
}

JSON form. A .tfvars.json file is a JSON object whose keys are variable names. Complex values in environment variables or a command-line assignment must be valid JSON on one line, because the shell does not know HCL.

The three sources disagree about typos. An environment variable with no matching block is ignored silently. A command-line assignment for an undeclared variable is an error. A tfvars entry for an undeclared variable produces a warning. When a value does not apply, check which behaviour you are seeing before editing the configuration.

Figure 4 draws the stack with a worked value, and makes the whole-value rule visible.

Variable value sources from weakest to strongest Six stacked sources feed one variable. The default is weakest, then TF_VAR environment variables, terraform.tfvars, terraform.tfvars.json, auto tfvars in lexical order, and finally command line options and HCP workspace variables. Each higher row replaces the whole value, so the effective replicas count is eight. Later sources win, and they replace the whole value -var and -var-file, in order given (HCP variables here) *.auto.tfvars and *.auto.tfvars.json, lexical order terraform.tfvars.json terraform.tfvars TF_VAR_service environment variable default in the variable block later wins worked trace default: 2 TF_VAR: 4 tfvars: 3 auto.tfvars: 6 -var: 8 effective: 8 Each row supplies the whole object, so no attribute is merged across sources. A remote run has no local flags: workspace variables and checked-in tfvars decide. Confirm the source list on the run itself instead of assuming a merge.

That last point matters for HCP Terraform and Terraform Enterprise. A remote run executes on a worker, not on your laptop, so your shell's TF_VAR_service and your -var flag are not there. Workspace variables, variable sets and the files committed to the repository are. The documentation groups workspace variables with command-line options at the top of the order, which is accurate about precedence but not about transport: on a remote run the top tier is populated from the workspace, not the terminal. Read the run's variable list when a value is not what you expected.

A defensible pattern is one committed terraform.tfvars for shared, non-secret defaults, an *.auto.tfvars file per environment generated by the pipeline, and environment variables only for short-lived or machine-specific values. Name auto files with a numeric prefix so lexical order is obvious, and never rely on two auto files setting the same variable.

Use Locals to Name Decisions Without Hiding Inputs

A local value is a name for an expression inside the module. It cannot be set by a caller, it does not appear in the interface, and it is not stored in state. Terraform evaluates it during each operation, so it always reflects the current inputs and resource attributes.

locals {
  name_prefix = "${var.environment}-${var.service.name}"
  effective_tags = merge(var.service.tags, {
    managed-by = "terraform"
    service    = var.service.name
  })
  container_ports = [for p in var.service.ports : {
    containerPort = p
    protocol      = var.service.protocol
  }]
  replica_ceiling = var.environment == "prod" ? 12 : 3
}

Those four locals do different jobs, and each one turns a repeated expression into a name.

LocalWhat it namesWhy it stays a local
name_prefixOne naming convention for environment and serviceKeeps three resources from drifting apart
effective_tagsCaller tags merged with platform tagsPrecedence becomes one reviewable decision instead of per-resource ordering
container_portsThe caller's port list in the shape the resource expectsAvoids repeating the conversion for every listener
replica_ceilingA production-versus-other-environment policy thresholdA validation or precondition can reference one number

The dividing line is ownership. A variable is a decision the caller is allowed to make. A local is a decision the module author makes on the caller's behalf. If an operations team needs to change a value per environment, it is a variable, even if the module currently computes it. If the value is derived, repeated, or expresses an invariant such as "every object gets managed-by = terraform", it is a local.

Locals become a problem when they hide an input. A module that reads var.environment and then hardcodes a bucket name in a local is not configurable; it only looks configurable. The same is true of a local that silently substitutes a default for a missing variable, because the caller never learns that their value was ignored. And a local is not a secret store: if a local holds a credential and a resource argument uses it, that value can reach state.

Locals are also not a solution to ordering. They may reference each other freely, and Terraform resolves the graph, but a cycle is an error rather than a warning. Keep the chain shallow: inputs, then a few derived names, then resources. A local that depends on six other locals is harder to review than the expression it replaced.

One operational caveat belongs here. Locals that feed for_each keys are part of the object's address. Changing how a local builds its map can rename keys, and renamed keys are destroy-and-create operations, not in-place updates. When a local builds identity, treat a change to it with the same care as renaming a resource.

Outputs Are an API with Exposure Consequences

Inputs are what a module accepts. Outputs are what it promises. A child module's outputs are its only public surface: the parent can read an exported output and nothing else inside the module. A root module's outputs are the values Terraform prints after apply, the values a pipeline reads with terraform output, and the values another configuration can read through the terraform_remote_state data source. That makes outputs a published interface even when the module is never shared.

A child output is not visible at the root until the root re-exports it:

output "service_endpoint" {
  description = "In-cluster DNS name and first declared port for the service."
  value       = module.service.endpoint
}

That three-line block is the whole re-export pattern, and forgetting it is the most common "the output is missing" bug. The child computed the value; the root never published it.

Write the description for the consumer, not for yourself. description = "The service endpoint." says nothing; description = "In-cluster DNS name and first declared port, for example orders-api.svc.cluster.local:8080." tells a caller what to do with it. Give the output a type constraint where the shape matters, so a change to the expression is checked against the promise instead of silently altering it.

Sensitivity is where outputs stop being cosmetic. Marking a variable sensitive = true redacts it in plan and apply output, and any expression that references it becomes sensitive too. Terraform then refuses to publish an output that contains a sensitive value unless the output is also marked sensitive, with an error along the lines of "Output refers to sensitive values". That refusal is a feature: it prevents a secret from being printed because someone added an output for debugging.

Redaction is not storage protection. The value is still written to state, and the CLI prints sensitive values in plain text for anyone with state access. terraform output -json or -raw is an explicit request, not a leak in the plan. Anyone who can read the state file, a saved plan, or a state backup can read the value.

Hosted runs add another surface. HCP Terraform shows output values in its interface, and marking an output sensitive in the workspace is a separate control from the configuration argument. If a token must not persist at all, the answer is an ephemeral variable with an ephemeral child output, which requires Terraform 1.10 or later and cannot be used on a root output.

Sensitive redacts the display, not the state

sensitive = true hides a value in plan output and requires a matching sensitive output. The value is still written to state and saved plans, and the output command prints it for anyone with state access. If it must not persist, use an ephemeral variable and an ephemeral child output.

Figure 5 shows both paths: the redacted plan line and the places the same value still appears.

The experiment below makes the difference visible with no provider and no cloud account.

Configuration

Outputs Are an API with Exposure Consequences

Execution status: design-only. The configuration is complete and valid for Terraform CLI 1.17.1, but this article does not claim the commands were run. Nothing here creates billable infrastructure.

Prerequisites. Terraform CLI 1.17.1 (terraform version must report it), an empty scratch directory, and no provider downloads. The module has no resources, only variables, locals and outputs.

Start with main.tf. It declares the version, a service variable, a sensitive token variable, and an output that deliberately forgets to mark the token:

terraform {
  required_version = "= 1.17.1"
}

variable "service" {
  type = object({
    name     = string
    replicas = number
    ports    = list(number)
    tags     = map(string)
  })
}

variable "registry_token" {
  type      = string
  sensitive = true
}

output "registry_token" {
  value = var.registry_token
}

Then terraform.tfvars supplies a complete object and a placeholder token:

service = {
  name     = "orders-api"
  replicas = 3
  ports    = [8080]
  tags     = { owner = "payments" }
}
registry_token = "example-not-a-real-token"
  1. Run terraform init -input=false. With no provider required, init should complete without downloading anything.
  2. Run terraform plan -input=false. Expect an error stating that the output refers to sensitive values, and naming the output block. The plan does not proceed.
  3. Add sensitive = true to the output and plan again. Expect a plan with no resource changes and the output shown as (sensitive value).
  4. Add a second output that returns only a derived, non-secret value, for example value = "${var.service.name}:${var.service.replicas}", and confirm it prints normally.
  5. Run terraform output -json. Expect the token in plain text, even though the plan redacted it. This is the exposure the flag warns about; do not run it against real credentials.
  6. Remove the token variable and its output before moving on, or delete the directory.

Expected observation. The unmarked output is rejected at plan time, the marked output is redacted in the plan, and the JSON command still reveals it. Sensitivity changes what Terraform prints, not what it stores.

Failure check. If the unmarked output plans successfully, check that sensitive = true is on the variable, not only on the output. If terraform output shows nothing, confirm you planned or applied at least once so the output exists in state.

Cost and cleanup. Zero. No provider is installed and no remote object is created. Delete the scratch directory, and use a disposable placeholder rather than a real token.

Redaction is not protection for an output value A sensitive variable flows into an output. Marking the output sensitive produces a redacted plan line, but the value is still stored in state and printed by terraform output with the json or raw flag. An unmarked output is rejected at plan time. One value, four audiences variable "registry_token" sensitive = true redacted in plan output output, sensitive = true plan prints (sensitive value) state still stores the text output without sensitive plan stops with an error: Output refers to sensitive values no marking on the output state file plaintext attribute value backups and saved plans too terraform output -json prints the value in plain text -raw does the same remote state consumer reads root outputs directly no redaction in transit Treat an output as publication, not as storage. If a value must not persist, use an ephemeral variable and a child ephemeral output. Sensitivity changes what the CLI prints. It does not change who can read state.

A useful review question for any new output: who is allowed to see this value, and does the state backend have the same audience? If the answer differs, the output is in the wrong place.

Reject Bad Inputs with an Actionable Message

A type constraint catches shape. A validation block catches meaning. It sits inside a variable block, has a condition that must evaluate to true, and an error message Terraform prints when it does not. Validation runs while Terraform builds the plan, before any provider call, so a bad value costs seconds rather than a partial apply.

The condition may only refer to the variable it belongs to, through var.<name>. It cannot read another variable, a local, or a resource attribute. That restriction keeps the check fast and local, and it pushes cross-variable rules into a check block, a precondition, or an expression that combines the values.

Types catch shape; validation catches meaning

Validation runs while Terraform builds the plan, before any provider call, so a bad value costs seconds instead of a partial apply. It can only read the variable it belongs to, which keeps it fast and local.

Three rules cover most cases:

RuleUse it forShape of the expression
can()Format checks that must not raisecan(regex("^[a-z][a-z0-9-]{2,30}$", var.service.name))
alltrue([for ...])Element rules across a collectionalltrue([for p in var.service.ports : p > 0 && p < 65536])
Count before contentDuplicates and cardinalitylength(var.service.ports) == length(distinct(var.service.ports))

The message deserves as much care as the condition. A useful message names the variable, states the rule, shows the allowed range or an example, and suggests the fix. "Invalid value" fails all four tests. Terraform already prints the file, line and variable name beside the message, so repeating them wastes the reader's attention; what Terraform cannot know is why the rule exists.

This is the interface for the running example, with the whole-number rule included because number does not imply integer:

variable "service" {
  description = "One deployable service: identity, size, listeners and ownership tags."
  type = object({
    name     = string
    replicas = number
    ports    = list(number)
    tags     = map(string)
    image    = optional(string, "ghcr.io/example/api:1.4.0")
    protocol = optional(string, "tcp")
  })
  nullable = false

  validation {
    condition     = can(regex("^[a-z][a-z0-9-]{2,30}$", var.service.name))
    error_message = "service.name must be 3 to 31 characters of lowercase letters, digits and hyphens, starting with a letter, for example \"orders-api\"."
  }

  validation {
    condition     = var.service.replicas >= 1 && var.service.replicas <= 12 && floor(var.service.replicas) == var.service.replicas
    error_message = "service.replicas must be a whole number from 1 to 12. Split the service across deployments instead of scaling one past 12."
  }

  validation {
    condition     = length(var.service.ports) > 0 && length(var.service.ports) == length(distinct(var.service.ports)) && alltrue([for p in var.service.ports : p > 0 && p <= 65535])
    error_message = "service.ports must contain at least one unique TCP port from 1 to 65535, for example [8080, 9090]."
  }
}

A failing call now produces a message that points at the caller's decision rather than at a provider schema. The shape is:

Error: Invalid value for variable

  on variables.tf line 1, in variable "service":

service.replicas must be a whole number from 1 to 12. Split the service across deployments instead of scaling one past 12.

  This was checked by the validation rule at variables.tf:19,3-13.

Two limits are worth stating plainly. First, validation cannot see unknown values, so a condition that depends on an apply-time value is deferred and may fail later. Second, a validation that encodes a policy which changes often becomes a release blocker; if the rule is advisory, use a check block, which warns and continues instead of stopping the run. The choice follows the timing: a type and a validation block for what the caller supplies, a precondition for what the configuration assumes, a postcondition for what the provider produced, and a check for what should be reported without blocking.

Lab

Design a service interface

Execution status: design-only. The exercise is specified against Terraform CLI 1.17.1 and uses no provider, so the only cost is a few seconds of CPU. Nothing is applied to a cloud account.

Prerequisites. Terraform CLI 1.17.1 on the path, an empty directory, and a shell. No credentials, provider download or network access beyond the binary you already have.

  1. Create variables.tf with the service variable exactly as shown in this section, including the three validation blocks and nullable = false.
  2. Create terraform.tfvars with a valid object: name orders-api, replicas 3, ports [8080, 9090], tags { owner = "payments" }.
  3. Run terraform init -input=false and terraform validate. Expect Success! The configuration is valid. There are no resources, so init installs nothing.
  4. Break the count: set replicas = 0 and run terraform plan -input=false. Expect an error containing the replicas message, raised before any plan is produced. Set it back to 3.
  5. Break the list: set ports = [8080, 8080] and plan again. Expect the ports message, which is the duplicate rule, not the range rule. Set it back.
  6. Break the name: set name = "Orders_API" and plan. Expect the name message with its example. Restore the valid name.
  7. Break the type: set replicas = "three". Expect a conversion error naming the attribute and the expected type, raised earlier than the validation messages because conversion happens first.

For the precedence evidence, use the console rather than editing files. Export a different object in the environment, then read the effective value:

export TF_VAR_service='{"name":"orders-api","replicas":4,"ports":[8080],"tags":{"owner":"payments"}}'
echo 'var.service.replicas' | terraform console

Expect 3, because terraform.tfvars outranks TF_VAR_*. Then override on the command line, where the value replaces the whole object rather than merging one attribute:

echo 'var.service.replicas' | terraform console -var='service={"name":"orders-api","replicas":8,"ports":[8080],"tags":{"owner":"payments"}}'

Expect 8. Finish by removing the directory and running unset TF_VAR_service, so the next experiment starts clean.

Expected observation. Each broken value fails before a plan exists, and each message names the variable, the rule and an example. The same variable resolves to 3 from tfvars and 8 from the command line, with no file edited between the two reads.

Failure checks. If replicas = 0 plans successfully, the validation block is missing or its condition is inverted. If a validation references another variable, Terraform rejects the block with an invalid-reference error at validate time. If ports = [] passes, the length check is missing: an empty list is a valid value, not a missing one.

Cost and cleanup. Zero. No provider, no state, no remote object. Delete the directory and unset the environment variable.

The habit that makes this interface durable is small: every variable gets a type that matches what the body needs, every rule gets a message a stranger can act on, every derived decision gets a local name, and every published value is treated as something a consumer will depend on. A module that follows those four rules can be reviewed from its variables.tf and outputs.tf alone, which is the point of calling it an interface.

Next in the Series

In Expressions and Functions: Turn Inputs into Infrastructure Data, we'll explore Use Terraform console to reason about strings, collections, encodings, CIDRs and conditional values.