Input variables and validation

Beginner · 11 min

Turn hard-coded values into input variables, learn which of six sources wins when several set one, and make bad values fail at plan time with validation.

Before thisHCL syntax: blocks, arguments and expressions

Tech Tutorials with Piyush · 20 min · from 2:13

Input variables and validation

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Tech Tutorials with PiyushReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A `variable` block declares an input. Callers set it with `-var`, a `.tfvars` file or a `TF_VAR_` environment variable, and a `default` makes it optional.
  • When several sources set the same variable, the later one in a fixed order wins, and `-var` on the command line always wins last.
  • A `validation` block turns a bad value into a plan-time error with your own message, before any API call.
  • Since Terraform 1.9 a validation can reference other variables and data sources, not only the variable it guards.
  • `sensitive = true` hides a value in plan output. It does not encrypt it, and it still lands in state.

From a constant to a parameter

The first configuration has a region and an instance size written straight into the resource. It works for one environment. The day a second one is needed, there are two bad choices: copy the folder and edit the copy, or edit the value, apply, and edit it back. Both end with configurations nobody trusts.

An input variable turns that value into a parameter of your configuration, the way a function argument turns a constant into something the caller chooses. The code stays identical and only the inputs change.

Declaring and using

Written from the Terraform docs. I did not run it, since there is no Terraform on this machine:

variable "environment" {
  type        = string
  description = "Which environment this is."
  default     = "dev"
}

variable "instance_count" {
  type = number
}

resource "local_file" "marker" {
  filename = "${path.module}/${var.environment}.txt"
  content  = "instances: ${var.instance_count}\n"
}

You read a variable as var.environment. A variable with no default, like instance_count, is required. If nothing sets it, Terraform asks at the prompt, which is why CI should set TF_INPUT=false and fail loudly instead.

Common arguments in the block are type, description, default, sensitive and nullable. The next lesson covers complex types. Always write a description. It shows up in generated docs and in the registry.

Six places a value can come from

The values can come from the command line, files and the environment. The docs list the order of precedence, lowest to highest, for the root module:

  1. the default in the variable block,
  2. environment variables, TF_VAR_name,
  3. terraform.tfvars,
  4. terraform.tfvars.json,
  5. *.auto.tfvars and *.auto.tfvars.json, in lexical order,
  6. -var and -var-file options, in the order given, plus any set by HCP Terraform.

The last one wins. I wrote a tiny resolver for that order and fed it one variable set in more and more places:

eu-central-1   from default                   (set in 1 places)
us-east-1      from TF_VAR_ env               (set in 2 places)
eu-west-1      from terraform.tfvars          (set in 3 places)
ap-south-1     from *.auto.tfvars (lexical)   (set in 4 places)
sa-east-1      from -var / -var-file          (set in 5 places)

My resolver omits terraform.tfvars.json (step 4), but it follows the docs on everything else. The practical lesson: terraform.tfvars quietly beats an exported TF_VAR_, and a stray something.auto.tfvars in the folder beats both. When the plan uses a value you did not expect, count the sources. The environments lesson builds a layout on top of this.

Validation: fail early, with your words

Without a check, a bad value travels. Someone passes environment = "prodution" and the typo ends up in resource names. A validation block stops it at plan time:

variable "environment" {
  type    = string
  default = "dev"

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

The condition is any expression that returns true or false, and error_message is shown when it is false. The Terraform docs say validations run while Terraform creates a plan, so the failure arrives before any API call. You can add several validation blocks to one variable.

The Terraform 1.9 changelog adds a significant change. Input variable validation rules “can refer to other objects” instead of only the variable being validated. Before 1.9 you could not express “if tls is true, certificate_arn must be set”. Now a validation on one variable can look at another variable or a data source. I checked this in the v1.9 changelog on GitHub. Ned in the Cloud’s video in deeper demonstrates it, and it is the reason the link is there.

Validation is for inputs. If you need to check something about a resource after it exists, that is a different tool, the precondition and postcondition covered in the lifecycle group.

Sensitive values

sensitive = true makes Terraform print (sensitive value) instead of the value in plan and apply output. Use it for passwords and tokens. It does not encrypt anything. The value still appears in the state file in plain text, and the saved plan too. Hiding output is only a courtesy to people reading logs. The full story is in sensitive values and secrets in state.

Habits that scale

  • Give every variable a type and a description.
  • Use defaults for choices that have a safe answer, and leave dangerous ones required, so nobody applies without deciding.
  • Do not pass secrets with -var on a shared machine, since command lines show up in process lists and shell history. Use TF_VAR_ from a secret store or a file with tight permissions.
  • Commit .tfvars files for non-secret per-environment values. Never commit one with secrets.

About the video

The embed is Tech Tutorials with Piyush’s “Day 5/28 - Terraform Variables - Input vs Output vs Local Variables”, January 2025, from the example through the “Other methods” section (2:13 to 13:24). The next lesson uses the last part of the same video. The channel runs a long beginner series, and the English auto-caption track is English. It is an Indian-English presenter and AWS-leaning. Its chapters list defining a variable and other methods of setting one, but not validation, which is why the Ned in the Cloud video is in deeper. I judged the video from its description and chapters.

Where this fits

Inputs go in. Next, how values come out of a configuration and how to name intermediate results so a long expression is only written once: outputs and locals.

Check yourself

  1. 01`TF_VAR_region=us-east-1` is exported, and `terraform.tfvars` sets `region = "eu-west-1"`. Which value does the plan use?

    `eu-west-1`. A `terraform.tfvars` file is read after environment variables, so it overrides them. Only `*.auto.tfvars` files and `-var` options rank higher.

  2. 02Why put a validation block on a variable when the provider will reject a bad value anyway?

    Your block fails during plan with your own message and no API calls, while a provider error may appear halfway through apply with a vendor's wording.

  3. 03What does marking a variable `sensitive = true` protect, and what does it not?

    It hides the value in plan and apply output. The value is still written in plain text to the state file, so state must be protected too.

  4. 04You want a validation that checks one variable against another. Which Terraform version first allowed it?

    1.9. Before that a validation condition could refer only to the variable being validated.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark