# Variables, locals and outputs

Make configurations reusable with typed variables and validation, .tfvars files, locals and outputs, and catch bad assumptions with preconditions.

Course: [Terraform](https://devops.rajeev.pro/courses/terraform), lesson 6. About 30 minutes, intermediate. Source: https://devops.rajeev.pro/courses/terraform/06-variables-outputs

## What you will learn

- Declare input variables with types, defaults, descriptions and validation rules
- Set values with .tfvars files, -var flags and TF_VAR_ environment variables, and know which wins
- Use locals to name values you'd otherwise repeat
- Return values with outputs and read them with terraform output
- Check assumptions with preconditions and postconditions

> **Lab status.** **Verified lab:** the validation error, -var-file plan, outputs and the failing precondition. Run on Terraform 1.17.1; the output shown is real. <br />**Code walkthrough:** the postcondition and check block examples: explained, not run. <br />**Cloud lab:** none; nothing here needs a cloud account.

Hard-coded values make a configuration good for exactly one thing. Variables turn it into
something you can run for dev and prod, for any team, without copying files. Think of a
configuration as a function: **variables** are its parameters, **locals** are its internal
variables, **outputs** are its return values.

> **Figure.** Values come from six places, lowest to highest precedence: the variable's default, TF_VAR_env environment variables, terraform.tfvars, star dot auto dot tfvars files, -var-file, and -var on the command line. They feed variable env with a type, a validation block and optionally sensitive. Locals name values such as prefix equals shop dash env. Resources use variables and locals and can carry preconditions and postconditions. Outputs return values to terraform output, to CI and to other configurations.
>
> Variables in, locals inside, outputs out. The bottom source on the left wins.

## Input variables

```hcl
# variables.tf
variable "env" {
  description = "Environment name: dev, staging or prod."
  type        = string

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

variable "servers" {
  description = "Server name => size."
  type        = map(string)
  default = {
    web = "t3.micro"
    api = "t3.small"
  }
}

variable "replicas" {
  description = "How many worker files to create."
  type        = number
  default     = 2
}
```

Each argument earns its place:

- **`type`** makes Terraform reject the wrong shape early: a string where a number belongs, a list
  where a map belongs.
- **`default`** makes the variable optional. `env` has none, so it's required and Terraform asks
  for it (or fails in CI).
- **`description`** shows up in docs and prompts. Write it for the next person.
- **`validation`** checks the value with your own rule and message. You can have several.
- Also available: `sensitive = true` (hide the value in output, see the Security lesson) and
  `nullable = false`.

Use it anywhere in the module as `var.env`. Here's validation stopping a typo before anything is
planned:

```text
$ terraform plan -var="env=test"

Planning failed. Terraform encountered an error while generating this plan.

Error: Invalid value for variable

  on variables.tf line 1:
   1: variable "env" {
    ├────────────────
    │ var.env is "test"

env must be dev, staging or prod.

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

## tfvars files

Typing `-var` for every value doesn't scale. Put the values for one environment in a `.tfvars`
file:

```hcl
# dev.tfvars
env      = "dev"
replicas = 1
```

```sh
$ terraform plan -var-file=dev.tfvars
```

Terraform also loads two kinds of files **automatically**, with no flag: `terraform.tfvars` and any
`*.auto.tfvars`. When the same variable is set in several places, the later one in this list wins:

1. The `default` in the variable block
2. Environment variables named `TF_VAR_<name>`, such as `TF_VAR_env=dev`
3. `terraform.tfvars`, then `terraform.tfvars.json`
4. `*.auto.tfvars` files, in alphabetical order
5. `-var` and `-var-file` on the command line, in the order you wrote them

A common setup: `dev.tfvars`, `staging.tfvars` and `prod.tfvars` in Git, and CI passing the right
one with `-var-file`. Keep secrets out of tfvars files; `TF_VAR_` variables set by CI from its secret
store are the usual way in.

## Locals

```hcl
# main.tf
locals {
  prefix = "shop-${var.env}"
  common = "managed-by: terraform\nenv: ${var.env}\n"
}
```

A **local** names an expression so you write it once. Every file name in this project uses
`local.prefix`, so renaming the scheme is a one-line change. Unlike variables, locals can't be set
from outside, which is the point: they're for values derived inside the module.

Good uses: name prefixes, merged tag maps (`merge(var.tags, { env = var.env })`), and values computed
from several variables. A local used only once is just indirection; inline it.

## Outputs

```hcl
# outputs.tf
output "server_files" {
  description = "File created for each server."
  value       = { for k, f in local_file.server : k => f.filename }
}

output "worker_count" {
  value = length(local_file.worker)
}
```

After apply, Terraform prints outputs, and you can read them any time:

```sh
$ terraform output
server_files = {
  "api" = "./out/shop-dev-api.txt"
  "web" = "./out/shop-dev-web.txt"
}
worker_count = 1
$ terraform output -json server_files
{"api":"./out/shop-dev-api.txt","web":"./out/shop-dev-web.txt"}
```

Outputs have three audiences: **people** (the load balancer URL after apply), **scripts and CI**
(`terraform output -raw url` in a deploy step), and **other configurations** (module outputs in
lesson 10, remote state in lesson 15). Only output what someone needs; every output is a contract.

## Preconditions and postconditions

Validation can only look at one variable. A **precondition** checks any assumption before Terraform
plans or applies a resource, such as a relationship between variables or a data source's result:

```hcl
resource "local_file" "summary" {
  filename = "${path.module}/out/${local.prefix}-summary.txt"
  content  = join("\n", [for k, f in local_file.server : "${k}: ${f.filename}"])

  lifecycle {
    precondition {
      condition     = length(var.servers) > 0
      error_message = "Define at least one server."
    }
  }
}
```

```text
$ terraform plan -var-file=dev.tfvars -var='servers={}'

Error: Resource precondition failed

  on main.tf line 28, in resource "local_file" "summary":
  28:       condition     = length(var.servers) > 0
    ├────────────────
    │ var.servers is empty map of string

Define at least one server.
```

A **postcondition** checks the result after a resource is created or read, using `self`, for example
"the AMI we found must be x86_64": `condition = self.architecture == "x86_64"`. A top-level `check`
block runs assertions on every plan and apply but only warns, which suits health checks like "the
website returns 200".

The four look similar but fail differently, which matters in production:

| Check                      | Looks at                                               | When it runs                              | If it fails                       |
| -------------------------- | ------------------------------------------------------ | ----------------------------------------- | --------------------------------- |
| `validation` in a variable | One input value                                        | Before planning                           | **Blocks** the run                |
| `precondition`             | Any assumption: several variables, data source results | Before planning or applying that resource | **Blocks** the run                |
| `postcondition`            | The resource or data source's own result (`self`)      | After it's read or applied                | **Blocks** what depends on it     |
| `check` block              | Anything, including live data                          | Every plan and apply                      | **Warns only**; the run continues |

So use validation for bad input, preconditions and postconditions for assumptions that must hold,
and `check` blocks for "tell me if this looks wrong" monitoring. A `check` is never a safety gate.

## Mission: Add a prod environment safely

Using the servers project from this lesson, create prod.tfvars with env = prod, three replicas and a third server, db = t3.medium. Plan with it, then prove validation works by planning with env = production. Record the outputs a prod apply would create.

- You need: variables.tf, main.tf and outputs.tf from this lesson
- You'll have: prod.tfvars

```sh
$ printf 'env      = "prod"\nreplicas = 3\nservers  = { web = "t3.small", api = "t3.medium", db = "t3.medium" }\n' > prod.tfvars
$ terraform plan -var-file=prod.tfvars | grep -E 'will be created|Plan:'
$ terraform plan -var-file=prod.tfvars -var='env=production'
```

The first plan should create 3 server files, 3 workers and the summary (7 to add). The second should
fail with "env must be dev, staging or prod." Note the order: the `-var` after `-var-file` wins.

## Try it

- Add a validation block to a variable and pass a bad value with -var to see the error.
- Create `dev.tfvars` and run `terraform plan -var-file=dev.tfvars`.
- Set `TF_VAR_env=staging` in your shell and run plan without -var.
- Add an output and read it with `terraform output -json`.
- Do the mini mission and keep `prod.tfvars`.

## Quiz

1. `TF_VAR_env=staging` is set, terraform.tfvars has `env = "dev"`, and you run `plan -var="env=prod"`. Which value is used?
   - staging
   - dev
   - **prod** (answer)
   Why: Command-line -var and -var-file win over terraform.tfvars, which wins over TF_VAR_ environment variables, which win over the default.

2. What is a local value for?
   - Storing secrets
   - **Naming an expression once inside a module so you don't repeat it, like a prefix used in ten names** (answer)
   - Taking input from the user
   Why: Locals are internal to the module. Variables are inputs from outside, outputs are results to the outside.

3. Where should a rule like "env must be dev, staging or prod" live?
   - In a comment
   - **In a validation block on the variable, so a bad value fails at plan time with a clear message** (answer)
   - In the README
   Why: Validation stops bad input before anything is created, with your own error message.

4. What does a precondition in a resource's lifecycle block check?
   - The provider version
   - **An assumption that must be true before Terraform plans or applies that resource, failing the run with your message if not** (answer)
   - The formatting of the file
   Why: Preconditions catch situations validation can't, such as relationships between variables or data source results.

## Resources

- [Input variables](https://developer.hashicorp.com/terraform/language/values/variables) (HashiCorp)
- [Variable definition precedence](https://developer.hashicorp.com/terraform/language/values/variables#variable-definition-precedence) (HashiCorp)
- [Local values](https://developer.hashicorp.com/terraform/language/values/locals) (HashiCorp)
- [Output values](https://developer.hashicorp.com/terraform/language/values/outputs) (HashiCorp)
- [Custom conditions (validation, preconditions, checks)](https://developer.hashicorp.com/terraform/language/expressions/custom-conditions) (HashiCorp)
