Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 37 ยท Variables, Outputs and Data Sources

Variable Validation and Sensitive Values

Reject bad input early with Terraform validation blocks, handle secrets with sensitive and ephemeral variables, understand what ends up in state, and use check blocks.

Types catch the kind of mistake: a string where a number belongs. They cannot catch "this string is not a valid environment name" or "this CIDR block is too small." Without further checks, a bad value travels all the way to the cloud API, where it fails minutes into an apply with an obscure message. Validation blocks stop it at the start with your message. The second half of this lesson covers a related duty: keeping secrets out of logs, plans and, as far as possible, state.

HCL is read-only; the stand-ins run the same logic in Python.

validation blocks

Add one or more validation blocks inside a variable:

HCL
variable "environment" {
  type        = string
  description = "Deployment environment."

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

condition is an expression returning true or false and may reference only the variable itself (since Terraform 1.9 it may also reference other variables, data sources and locals). error_message should say what is wrong and what is allowed. If the condition is false, Terraform stops before planning:

TEXT
Error: Invalid value for variable

  on variables.tf line 1:
   1: variable "environment" {
    var.environment is "test"

environment must be one of: dev, staging, prod.

(Example output.)

Useful validation patterns

HCL
variable "bucket_name" {
  type = string
  validation {
    condition     = can(regex("^[a-z0-9][a-z0-9-]{2,62}$", var.bucket_name))
    error_message = "Use 3-63 lowercase letters, digits or hyphens, starting with a letter or digit."
  }
}

variable "cidr_block" {
  type = string
  validation {
    condition     = can(cidrhost(var.cidr_block, 0))
    error_message = "cidr_block must be a valid IPv4 CIDR such as 10.0.0.0/16."
  }
}

variable "replicas" {
  type = number
  validation {
    condition     = var.replicas >= 1 && var.replicas <= 20 && floor(var.replicas) == var.replicas
    error_message = "replicas must be a whole number from 1 to 20."
  }
}

variable "ports" {
  type = list(number)
  validation {
    condition     = alltrue([for p in var.ports : p > 0 && p < 65536])
    error_message = "Every port must be between 1 and 65535."
  }
}

The recurring trick is can(...): it converts "this expression raises an error" into false, so functions like regex, cidrhost or tonumber become tests. alltrue and anytrue check lists of booleans. You may write several validation blocks per variable; each reports its own message, so split independent rules rather than combining them with &&.

Python Running validation rules (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Sensitive variables

Mark a variable sensitive = true and Terraform redacts it in plan and apply output:

HCL
variable "db_password" {
  type      = string
  sensitive = true
}

resource "aws_db_instance" "main" {
  password = var.db_password
}
TEXT
  + password = (sensitive value)

Sensitivity is contagious: any expression that uses a sensitive value is also sensitive, including outputs. An output that derives from a sensitive value must be declared sensitive = true as well, or Terraform errors to protect you. nonsensitive(value) strips the flag when you are sure the result is safe, for example a boolean derived from a secret.

sensitive only hides a value from CLI output. The value is still stored in plain text in the state file (and in saved plan files). Anyone who can read the state can read your database password. Protect state with an encrypted remote backend and strict access control; see the State Management chapter. Also never put secrets in default values or committed tfvars.

Python Sensitive values are masked, contagious and still stored (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last line is the lesson: masking is cosmetic. Treat state like a password vault.

Ephemeral values and write-only arguments

Terraform 1.10 introduced ephemeral values: they exist while Terraform runs but are never saved to state or plan files. Mark a variable with ephemeral = true, read secrets through ephemeral resources, and pass them to write-only arguments (names ending in _wo, available in newer provider versions):

HCL
variable "db_password" {
  type      = string
  ephemeral = true
}

resource "aws_db_instance" "main" {
  password_wo         = var.db_password
  password_wo_version = 1
}

Because the provider never stores a write-only value, there is nothing to leak. To rotate it, bump password_wo_version. Check that your provider version supports the _wo arguments for the resource you use; OpenTofu offers its own state encryption as a complementary option.

check blocks and post-apply assertions

A check block runs assertions at the end of plan and apply and reports warnings, not errors. It suits health checks that should not block a deployment:

HCL
check "site_is_up" {
  data "http" "home" {
    url = "https://${aws_lb.front.dns_name}/health"
  }

  assert {
    condition     = data.http.home.status_code == 200
    error_message = "Health check did not return 200."
  }
}

Compare the three assertion tools: validation guards inputs (hard stop, before planning), precondition and postcondition guard a resource or output (hard stop), check observes the world (warning).

Where secrets should come from

  1. Environment variables (TF_VAR_db_password) set by the CI system from its secret store.
  2. Secret managers read through a data source or ephemeral resource (AWS Secrets Manager, Vault, Key Vault). The secret is generated outside, so Terraform only references it.
  3. Generated secrets with the random_password resource. They live in state, so combine with an encrypted backend.
  4. Never in .tf files, default values or committed .tfvars.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does can(regex("^[a-z]+$", var.name)) return for the value "Web1"?

    regex raises an error when there is no match; can() turns that error into false, which makes it usable as a validation condition.
  2. 2. Is a variable marked sensitive = true stored encrypted in the state file?

    Sensitive masks values in output. The state file contains the actual value, so protect the state.
  3. 3. What happens to an output that uses a sensitive variable and is not marked sensitive?

    Sensitivity propagates. Terraform refuses to expose a derived value unless the output is declared sensitive.
  4. 4. Which feature keeps a value out of both the state and plan files?

    Ephemeral values (Terraform 1.10+) live only during the run; write-only arguments are never persisted.

Summary

  • validation blocks reject bad input early with your own error_message; can() converts errors into booleans.
  • Use several validation blocks per variable, one rule each.
  • sensitive = true masks values in output and is contagious, but state still holds plain text.
  • Ephemeral variables and write-only arguments keep secrets out of state entirely.
  • precondition/postcondition guard resources; check blocks warn about runtime conditions.
  • Feed secrets through the environment or a secret manager, never through committed files.

Next: Local Values and Outputs