# Variables and Validation — Terraform

Source: https://www.skillbyai.com/en/terraform/l-vars

> Inputs with types and rules.

## Typed inputs that fail early

Input **variables** parameterise a configuration: declare a `type` (string, number, bool, list, map, object), a `description` and optionally a `default`. Set values with `-var`, `.tfvars` files, or `TF_VAR_name` environment variables. A **validation** block rejects invalid values at plan time with your message, long before an API call fails. Mark variables holding secrets as `sensitive = true`.

## A rejected variable value, run

I ran this with Terraform 1.16.4 and the hashicorp/local 2.9.1 and hashicorp/random 3.9.1 providers, which manage local files and random values, so no cloud account was needed; each example starts from a fresh directory. Passing env=qa fails the validation rule and plan stops with the custom message, before any change is attempted.

```bash
terraform plan -no-color -var env=qa 2>&1 | grep -E "Error|env must be"
```

Output:

```
Error: Invalid value for variable
env must be dev, staging or prod.
```

## Use tfvars per environment

Keep dev.tfvars and prod.tfvars (without secrets) so environment differences are explicit and reviewable.

**Quiz:** When does a variable validation rule run?

- [ ] After apply
- [x] At plan time, before any infrastructure change
- [ ] Only in the cloud console
- [ ] Never automatically

*Answer:* At plan time, before any infrastructure change. Fail fast on bad input.
