In the previous lesson you learnt the grammar of HCL2 and ended up turning a tangle of conditionals into a sizing map per environment. That map, however, was still a local: it was baked into the code and nobody could change it from outside. This lesson builds the interface of a Terraform configuration: the input variables, which let the same code serve dev, staging and prod, and the outputs, which expose the results to people, to scripts and to other modules. Mastering this interface is what separates a configuration that only works on your laptop from a reusable module a whole team can consume with confidence.
- Why input variables exist
EcoMarket needs to deploy the same architecture three times: dev, staging and prod. Without variables, the options would be to copy the code three times (and let it diverge) or to edit values by hand before every apply (and get it wrong).
An input variable turns a configuration into a parameterisable function:
flowchart LR
subgraph INPUT["Inputs"]
V1["terraform.tfvars"]
V2["-var / -var-file"]
V3["TF_VAR_*"]
end
subgraph CONFIG["EcoMarket configuration"]
VAR["variable"] --> LOC["locals"] --> RES["resource / data"]
RES --> OUT["output"]
end
subgraph OUTPUT["Outputs"]
S1["terraform output"]
S2["parent module"]
S3["scripts and CI"]
end
V1 --> VAR
V2 --> VAR
V3 --> VAR
OUT --> S1
OUT --> S2
OUT --> S3
There is a design rule worth settling before going further: parameterise what changes between environments, not everything that could change. One variable per argument of every resource produces modules nobody can use. EcoMarket parameterises the environment, the region, the sizing and the connection credentials; the name of the inventory file, by contrast, is derived with locals.
- The
variable block in full
variable block in fullThese are all the arguments it accepts:
variable "environment" {
# description: what it is. It appears in the interactive prompts, in
# `terraform output`, in the documentation generated with terraform-docs
# and in the Registry if you publish the module. In practice it is not optional.
description = "EcoMarket deployment environment: dev, staging or prod."
# type: restricts which values are accepted. Checked BEFORE anything is touched.
type = string
# default: the value if nobody assigns another. Without a default, the variable
# is MANDATORY: Terraform will ask for it at the keyboard or fail in CI.
default = "dev"
# nullable: can null be assigned explicitly? True by default.
# With false, assigning null makes the default be used instead.
nullable = false
# sensitive: hides the value in the plan and apply output.
sensitive = false
# validation: your own rules, as many as you like.
validation {
condition = contains(["dev", "staging", "prod"], var.environment)
error_message = "The environment must be dev, staging or prod. Received: ${var.environment}."
}
}The nuances that make the difference:
| Argument | Default value | What you need to know |
|---|---|---|
description |
empty | Always write it; it is executable documentation |
type |
any |
Without type, Terraform accepts anything and the error arrives late |
default |
— | Its absence makes the variable mandatory |
nullable |
true |
nullable = false avoids the odd "explicit null value" case |
sensitive |
false |
Hides it in the output, not in the state |
validation |
— | Evaluated before the plan; there can be several blocks |
Mandatory versus optional variables. A variable with no default causes this if nobody gives it a value:
In a terminal it is a useful prompt; in a pipeline it is a hang until the timeout. That is why CI uses -input=false, which turns the question into an immediate error:
$ terraform plan -input=false
╷
│ Error: No value for required variable
│
│ on variables.tf line 45:
│ 45: variable "db_password" {
│
│ The root module input variable "db_password" is not set, and has no default
│ value. Use a -var or -var-file command line argument to provide a value for
│ this variable.
╵About nullable. It is the least used argument and the one that prevents the most confusion:
variable "custom_domain" {
description = "The shop's own domain. null uses the load balancer's default domain."
type = string
default = null
# nullable = true (the default): null is a LEGITIMATE and meaningful value.
}
variable "environment" {
description = "Deployment environment."
type = string
default = "dev"
nullable = false
# If somebody passes environment = null, "dev" is used instead of propagating a
# null that would break local.prefix further down the line.
}Practical rule: nullable = false for anything that makes no sense as "no value", and default = null with nullable = true when "not set" is a real option that defers to the provider.
- Complex types:
object, map(object(...)) and optional()
object, map(object(...)) and optional()This is where the type system from the previous lesson starts to pay off. EcoMarket needs to describe its PostgreSQL database configuration with several attributes of different types: that is an object.
variable "db_config" {
description = <<-EOT
Configuration of EcoMarket's PostgreSQL database.
Attributes marked as optional() take the value shown
if the consumer does not supply them.
EOT
type = object({
# MANDATORY attributes: whoever uses this configuration must supply them.
engine = string
version = string
# OPTIONAL attributes with a default value.
# optional(TYPE, DEFAULT_VALUE) is the modern form (Terraform >= 1.3).
port = optional(number, 5432)
storage_gb = optional(number, 20)
multi_az = optional(bool, false)
retention_days = optional(number, 7)
backup_window = optional(string, "02:00-03:00")
# optional(TYPE) with no second argument: the default value is null.
extra_params = optional(map(string))
})
default = {
engine = "postgres"
version = "16.3"
}
}Exactly what happens with optional(). If the consumer writes only:
Terraform completes the object before your code ever sees it:
$ terraform console
> var.db_config
{
"backup_window" = "02:00-03:00"
"engine" = "postgres"
"extra_params" = null
"multi_az" = false
"port" = 5432
"retention_days" = 7
"storage_gb" = 20
"version" = "16.3"
}This is enormously valuable: inside the configuration you can write var.db_config.port without checking whether it exists. Without optional() you would need lookup() and default values scattered all over the code.
Now EcoMarket's star case: describing all three environments in a single variable with map(object(...)).
variable "environments" {
description = "Definition of every EcoMarket environment, indexed by name."
type = map(object({
# Web tier sizing
web_instances = number
web_class = optional(string, "t3.micro")
# Database
db_class = optional(string, "db.t3.micro")
retention_days = optional(number, 7)
multi_az = optional(bool, false)
# Behaviour
protect_deletion = optional(bool, false)
extra_tags = optional(map(string), {})
}))
default = {
dev = {
web_instances = 1
}
staging = {
web_instances = 2
db_class = "db.t3.small"
retention_days = 14
}
prod = {
web_instances = 3
web_class = "t3.small"
db_class = "db.t3.medium"
retention_days = 30
multi_az = true
protect_deletion = true
extra_tags = {
CostCenter = "CC-1042"
Compliance = "pci"
}
}
}
}And this is how it is consumed:
locals {
# Configuration of the currently selected environment.
# Bracket access fails loudly if the environment does not exist,
# which is exactly what we want: better an error than a silent deployment.
current = var.environments[var.environment]
prefix = "${var.project}-${var.environment}"
common_tags = merge(
{
Project = var.project
Environment = var.environment
ManagedBy = "terraform"
},
local.current.extra_tags, # the environment's extra tags are added on top
)
}Compare this design with the locals from the previous lesson: the code is the same, but now the environment catalogue can come from outside. A team that wants a fourth sandbox environment only has to add an entry to its .tfvars, without touching the module.
A quick decision table on which type to declare:
| You need... | Declare | EcoMarket example |
|---|---|---|
| A name, a region | string |
var.environment, var.region |
| A switch | bool |
var.enable_cdn |
| A quantity | number |
var.web_instances |
| A homogeneous, ordered list | list(string) |
var.availability_zones |
| A set with no order and no duplicates | set(string) |
var.allowed_origins |
| Arbitrary tags | map(string) |
var.extra_tags |
| A group of related settings | object({...}) |
var.db_config |
| Several groups indexed by name | map(object({...})) |
var.environments |
| An unknown structure (avoid it) | any |
— |
A warning about any: it is tempting, but it switches off all type validation and produces confusing errors inside the resources. Use it only when you genuinely accept any structure, for example for a map(string) of free-form tags… and then declare map(string).
- The six ways of assigning values and their precedence
Terraform gathers values from six sources. The order matters because the last one to assign wins.
| # | Source | Precedence | How it is triggered |
|---|---|---|---|
| 1 | The variable block's default |
Lowest | Automatic |
| 2 | TF_VAR_<name> environment variables |
Low | Automatic if they exist |
| 3 | terraform.tfvars (or terraform.tfvars.json) |
Medium | Automatic if the file exists |
| 4 | *.auto.tfvars / *.auto.tfvars.json |
Medium-high | Automatic, in alphabetical order |
| 5 | -var-file=file |
High | Explicit, in command-line order |
| 6 | -var="name=value" |
Highest | Explicit, in command-line order |
The usual surprise is number 2: TF_VAR_* has LOW precedence, below any .tfvars file. Plenty of people assume the opposite and lose an afternoon debugging why their environment variable "is not applied" when in reality a terraform.tfvars they had forgotten about is overriding it.
Another nuance: items 5 and 6 are processed in the order they appear on the command line. If you write -var="environment=prod" -var-file=dev.tfvars, the file wins, because it comes later.
Let us see it in action. We start from this declaration:
# variables.tf
variable "environment" {
description = "Deployment environment."
type = string
default = "dev" # (1)
}# Files present in the directory
$ cat terraform.tfvars
environment = "staging" # (3)
$ cat 01-common.auto.tfvars
environment = "preproduction" # (4) — loaded first (alphabetical order)
$ cat 02-team.auto.tfvars
environment = "integration" # (4) — loaded later and OVERRIDES the previous one
$ cat production.tfvars
environment = "prod" # (5) — only if given with -var-fileResults, from least to most specific:
# The default alone: rename the files temporarily to try it out.
$ terraform console
> var.environment
"dev"
# With TF_VAR_: loses against terraform.tfvars
$ TF_VAR_environment=from_env terraform console
> var.environment
"staging"
# With the .auto.tfvars files present: the alphabetically last one wins
> var.environment
"integration"
# With an explicit -var-file
$ terraform console -var-file=production.tfvars
> var.environment
"prod"
# With -var: highest priority
$ terraform console -var-file=production.tfvars -var="environment=urgent"
> var.environment
"urgent"For complex types, the command-line syntax uses HCL:
# An object via -var (mind the shell quoting)
$ terraform plan -var='db_config={engine="postgres",version="16.3",port=5433}'
# A list
$ terraform plan -var='zones=["eu-west-1a","eu-west-1b"]'
# An environment variable holding an object: same HCL format
$ export TF_VAR_db_config='{engine="postgres",version="16.3"}'Security warning: any value you pass with
-varends up in the shell history (~/.bash_history) and may appear in the CI logs. For secrets, useTF_VAR_*fed from a secrets manager, never-var="password=...".
.tfvars and .auto.tfvars files in practice
.tfvars and .auto.tfvars files in practiceA .tfvars file is HCL without blocks: assignments only.
# dev.tfvars — values for EcoMarket's development environment
project = "ecomarket"
environment = "dev"
region = "eu-west-1"
db_config = {
engine = "postgres"
version = "16.3"
}
extra_tags = {
Owner = "plataforma"
}And the JSON variant, for when the file is generated by a program:
{
"project": "ecomarket",
"environment": "dev",
"region": "eu-west-1",
"db_config": {
"engine": "postgres",
"version": "16.3"
}
}When to use each name:
| Name | Loads by itself | Recommended use in EcoMarket |
|---|---|---|
terraform.tfvars |
Yes | Values for the directory's default environment |
terraform.tfvars.json |
Yes | The same, but generated by a script |
*.auto.tfvars |
Yes, alphabetically | Values common to every environment in a directory |
dev.tfvars, prod.tfvars |
No | Explicit selection with -var-file; stops you applying to prod by accident |
secrets.auto.tfvars |
Yes | Never: automatic and secret should not go together |
The layout EcoMarket adopts, consistent with what you will see in Code Organization:
ecomarket-infra/
└── infra/
├── main.tf
├── variables.tf
├── outputs.tf
├── versions.tf
├── common.auto.tfvars # project, region, contact: always the same
├── dev.tfvars # explicit: -var-file=dev.tfvars
├── staging.tfvars
└── prod.tfvars# A deployment always names the environment. No ambiguity is possible.
$ terraform plan -var-file=dev.tfvars -out=dev.tfplan
$ terraform apply dev.tfplanAnd the hygiene reminder you already started in module 1:
# .gitignore of the ecomarket-infra repository
*.tfstate
*.tfstate.*
.terraform/
*.tfplan
# Value files that MIGHT contain secrets.
# Per-environment .tfvars ARE committed if they only carry sizing.
secrets.tfvars
*.auto.tfvars.local
# The lock file IS committed (do not ignore it):
# !.terraform.lock.hcl
- Sensitive variables: what they hide and what they do not
Marking a variable as sensitive = true makes Terraform hide its value in the plan and apply output:
variable "db_password" {
description = <<-EOT
Password for the PostgreSQL administrator user.
Do NOT put it in a committed .tfvars file: pass it through
TF_VAR_db_password from the secrets manager.
EOT
type = string
sensitive = true
nullable = false
validation {
condition = length(var.db_password) >= 16
error_message = "The password must be at least 16 characters long."
}
}This is how it looks in the plan:
$ terraform plan
# local_file.credentials will be created
+ resource "local_file" "credentials" {
+ content = (sensitive value)
+ filename = "./ecomarket-dev-credentials.json"
+ file_permission = "0600"
}The sensitivity mark propagates: any value derived from a sensitive variable is hidden too, even if you do not mark it. If local.connection_string includes var.db_password, the whole local becomes sensitive, and so does any resource or output that uses it.
Now the important part, and the reason so many teams have a false sense of security:
Does sensitive = true… |
Protect it? |
|---|---|
The terraform plan and apply output in the terminal |
Yes |
| The CI pipeline logs | Yes (if they are printed through Terraform) |
The value inside terraform.tfstate |
NO: it is in plain text |
A plan file saved with -out |
NO: it is in plain text |
terraform output -json |
NO: it appears, flagged as "sensitive": true |
Debug logs with TF_LOG=TRACE |
NO |
| Whatever the provider sends to the API | NO (TLS protects that, not Terraform) |
Check it for yourself:
$ terraform apply -auto-approve
...
Outputs:
connection_string = <sensitive>
# But in the state it sits there in the open:
$ jq -r '.outputs.connection_string.value' terraform.tfstate
postgresql://ecomarket_admin:Example-Password-1234@ecomarket-dev-db:5432/ecomarket
# And in JSON too, even though it comes labelled:
$ terraform output -json | jq '.connection_string'
{
"sensitive": true,
"type": "string",
"value": "postgresql://ecomarket_admin:Example-Password-1234@..."
}Operational conclusion: sensitive stops a secret showing up in a screenshot or in the log of a pull request. Really protecting the secret requires encrypting and restricting access to the state, which is the subject of Remote State, plus the complete practices in Security Best Practices.
To read a sensitive value on purpose, Terraform forces you to ask for it explicitly:
# A deliberate error: it forces you to be aware
$ terraform output connection_string
╷
│ Error: Output refers to sensitive values
│
│ To reduce the risk of accidentally exporting sensitive data that was intended
│ to be only internal, Terraform will not mark outputs as sensitive by default.
╵
# The correct way to obtain it for a script
$ terraform output -raw connection_string
postgresql://ecomarket_admin:...And if you need to deliberately expose a value Terraform considers sensitive, there is nonsensitive(). Use it with judgement and with a comment justifying why it is safe:
output "db_port" {
# The port comes from var.db_config, which is sensitive as a whole,
# but the port number on its own reveals nothing.
value = nonsensitive(var.db_config.port)
}
- Validations with
condition and error_message
condition and error_messageA validation block turns implicit assumptions into clear errors before Terraform touches anything.
variable "environment" {
description = "EcoMarket deployment environment."
type = string
nullable = false
validation {
# condition must be a boolean expression.
condition = contains(["dev", "staging", "prod"], var.environment)
error_message = "The environment must be one of: dev, staging, prod. Received: '${var.environment}'."
}
}When it fails:
$ terraform plan -var="environment=production"
╷
│ Error: Invalid value for variable
│
│ on variables.tf line 10:
│ 10: variable "environment" {
│ ├────────────────
│ │ var.environment is "production"
│
│ The environment must be one of: dev, staging, prod. Received: 'production'.
│
│ This was checked by the validation rule at variables.tf:15,3-13.
╵Rules of the validation block:
- There can be several blocks on the same variable; all of them are evaluated and every failure is reported.
- The condition must return a
bool. If it raises an evaluation error instead of returningfalse, the message will be ugly: that is whatcan()is for. - Up to Terraform 1.8, the condition could only refer to
var.<this same variable>. Since Terraform 1.9 it can also refer to other variables and to data values, which enables the cross-validations in the next section. The EcoMarket project pinned1.9.8in.terraform-version, so we will use them. - The
error_messagemust be a complete sentence, ending in a full stop, stating what was expected and what arrived.
A realistic set for EcoMarket:
variable "region" {
description = "Region where EcoMarket is deployed."
type = string
default = "eu-west-1"
validation {
# AWS region format: two or three letters, hyphen, word, hyphen, digit.
condition = can(regex("^[a-z]{2,3}-[a-z]+-[0-9]$", var.region))
error_message = "The region must use the AWS format, for example eu-west-1. Received: '${var.region}'."
}
validation {
# Internal policy: EcoMarket only operates in Europe.
condition = startswith(var.region, "eu-")
error_message = "Under the data residency policy, EcoMarket only deploys to eu-* regions."
}
}
variable "web_instances" {
description = "Number of ecomarket-web instances behind the load balancer."
type = number
default = 1
validation {
condition = var.web_instances >= 1 && var.web_instances <= 10
error_message = "The number of instances must be between 1 and 10."
}
validation {
# floor(x) == x checks that it is an integer.
condition = floor(var.web_instances) == var.web_instances
error_message = "The number of instances must be an integer, not a decimal."
}
}
variable "alerts_email" {
description = "Mailbox that receives the platform's alerts."
type = string
default = "[email protected]"
validation {
condition = can(regex("^[\\w.+-]+@[\\w-]+\\.[\\w.-]+$", var.alerts_email))
error_message = "The alerts email address is not in a valid format."
}
}
can(), try() and regex() in validations
can(), try() and regex() in validationsThese three functions are what make validations robust. Here we see them applied; the full function catalogue is in Terraform Functions.
can(expression) runs the expression and returns true if it evaluates without error, false if it fails. It turns an error into a boolean.
locals {
# regex() RAISES AN ERROR when there is no match; it does not return false.
# That is why it is wrapped in can().
valid_region = can(regex("^eu-", var.region))
}try(expr1, expr2, ...) returns the first expression that evaluates without error. It is for accessing structures that may not exist:
locals {
# If the environment does not define extra_tags, use an empty map.
extra = try(var.environments[var.environment].extra_tags, {})
}regex(pattern, string) extracts a match, and regexall() returns all of them. Mind the escaping: inside an HCL string, \d has to be written \\d.
Now the cross-validations, which are the main reason for requiring Terraform 1.9:
variable "environment" {
description = "Deployment environment."
type = string
nullable = false
}
variable "environments" {
description = "Catalogue of available environments."
type = map(object({
web_instances = number
multi_az = optional(bool, false)
protect_deletion = optional(bool, false)
retention_days = optional(number, 7)
}))
validation {
# 1. The selected environment must exist in the catalogue.
# A reference to ANOTHER variable: requires Terraform >= 1.9.
condition = contains(keys(var.environments), var.environment)
error_message = "Environment '${var.environment}' is not defined in var.environments. Defined: ${join(", ", keys(var.environments))}."
}
validation {
# 2. Production MUST be protected against deletion and be highly
# available. A business rule turned into code.
condition = !contains(keys(var.environments), "prod") || (
var.environments["prod"].protect_deletion &&
var.environments["prod"].multi_az
)
error_message = "The 'prod' environment must have protect_deletion = true and multi_az = true."
}
validation {
# 3. Production's retention cannot be shorter than staging's.
# try() avoids failing if either environment is not defined.
condition = try(
var.environments["prod"].retention_days >= var.environments["staging"].retention_days,
true
)
error_message = "The backup retention for prod cannot be shorter than staging's."
}
}And a validation over an object, combining everything above:
variable "db_config" {
description = "PostgreSQL configuration for EcoMarket."
type = object({
engine = string
version = string
port = optional(number, 5432)
storage_gb = optional(number, 20)
})
validation {
condition = var.db_config.engine == "postgres"
error_message = "EcoMarket only supports PostgreSQL as its database engine."
}
validation {
# major.minor version, with major >= 14.
condition = can(regex("^[0-9]+\\.[0-9]+$", var.db_config.version)) && (
tonumber(split(".", var.db_config.version)[0]) >= 14
)
error_message = "The PostgreSQL version must look like '16.3' and be at least 14."
}
validation {
condition = var.db_config.port > 1024 && var.db_config.port <= 65535
error_message = "The port must be between 1025 and 65535."
}
validation {
condition = var.db_config.storage_gb >= 20
error_message = "The minimum storage for managed PostgreSQL is 20 GB."
}
}An important note: variable validations check inputs. To check results (for example, that the chosen AMI is 64-bit, or that the bucket ended up with encryption enabled) there are precondition and postcondition, studied in Preconditions, Postconditions and check Blocks.
- The
output block in full
output block in fullAn output publishes a value. Its arguments:
output "images_bucket_name" {
# description: what this value is for and who consumes it.
description = "Name of EcoMarket's product image bucket."
# value: any expression. It is the only mandatory argument.
value = "${local.prefix}-images-${random_id.suffix_hex.hex}"
# sensitive: hides the value in the apply output and in `terraform output`
# without flags. It does NOT encrypt it in the state.
sensitive = false
# depends_on: an explicit dependency. Only if the value depends on something
# Terraform cannot infer from the expression.
# depends_on = [local_file.bucket_policy]
}| Argument | Mandatory? | What for |
|---|---|---|
value |
Yes | The expression to publish |
description |
No (but write it) | Documents the module's contract |
sensitive |
No (false) |
Hides the value in the terminal |
depends_on |
No | Forces ordering when the expression does not reveal it |
precondition |
No | Checks a condition before publishing; covered in 06-05 |
Realistic EcoMarket outputs, with varying degrees of elaboration:
# outputs.tf
output "name_prefix" {
description = "Prefix used to name every resource in the environment."
value = local.prefix
}
output "environment_config" {
description = "Effective configuration of the selected environment, with the optional() values already resolved."
value = local.current
}
output "endpoints" {
description = "The platform's entry points, for the application team."
# A composite object: one rich output beats ten loose ones.
value = {
web = "https://${local.prefix}.ecomarket.example.com"
bucket = local_file.inventory.filename
environment = var.environment
region = var.region
}
}
output "db_connection_string" {
description = "Full connection string to PostgreSQL. It contains the password."
value = "postgresql://${var.db_user}:${var.db_password}@${local.prefix}-db:${var.db_config.port}/ecomarket"
sensitive = true
}
output "deployment_summary" {
description = "A readable summary to paste into the deployments channel."
value = <<-EOT
Environment: ${var.environment}
Region : ${var.region}
Instances : ${local.current.web_instances}
Retention : ${local.current.retention_days} days
Contact : [email protected]
EOT
}When to use depends_on on an output. It is rare, but it happens: when the consumer of the output needs something to be finished and that dependency does not appear in the value expression.
output "bucket_ready" {
description = "The bucket name, guaranteeing that its policy has already been applied."
value = local.bucket_name
# The expression does not mention the policy resource, but whoever consumes
# this output will assume the bucket is usable. With depends_on, the parent
# module will not receive the value until the policy exists.
depends_on = [local_file.bucket_policy]
}Sensitive outputs and propagation. If the value derives from something sensitive, Terraform forces you to mark the output:
$ terraform plan
╷
│ Error: Output refers to sensitive values
│
│ on outputs.tf line 30:
│ 30: output "db_connection_string" {
│
│ To reduce the risk of accidentally exporting sensitive data that was intended
│ to be only internal, Terraform requires that any root module output containing
│ sensitive data be explicitly marked as sensitive, to confirm your intent.
│
│ If you do intend to export this data, annotate the output value as sensitive
│ by adding the following argument:
│ sensitive = true
╵It is an excellent safeguard: you cannot expose a secret by accident, only on purpose.
- How outputs are consumed
Outputs are stored in the state when you apply and can be queried without planning again.
# All of them, in readable format
$ terraform output
db_connection_string = <sensitive>
endpoints = {
"bucket" = "./ecomarket-dev-inventory.json"
"environment" = "dev"
"region" = "eu-west-1"
"web" = "https://ecomarket-dev.ecomarket.example.com"
}
environment_config = {
"db_class" = "db.t3.micro"
"extra_tags" = {}
"multi_az" = false
"protect_deletion" = false
"retention_days" = 7
"web_class" = "t3.micro"
"web_instances" = 1
}
name_prefix = "ecomarket-dev"
# A specific one, with quotes (HCL format)
$ terraform output name_prefix
"ecomarket-dev"
# Raw, without quotes: the right form for scripts
$ terraform output -raw name_prefix
ecomarket-dev
# One attribute of a composite output, with jq
$ terraform output -json endpoints | jq -r '.web'
https://ecomarket-dev.ecomarket.example.com
# All of them in JSON, with type and sensitivity flag
$ terraform output -json | jq 'to_entries | map({key: .key, sensitive: .value.sensitive})'Real use in EcoMarket's deployment flow:
#!/usr/bin/env bash
# deploy-app.sh — publishes the application once the infrastructure is applied
set -euo pipefail
cd ~/projects/ecomarket-infra/infra
PREFIX=$(terraform output -raw name_prefix)
WEB_URL=$(terraform output -json endpoints | jq -r '.web')
echo "Deploying the ${PREFIX} application to ${WEB_URL}"
# The connection string is sensitive: it is passed through the environment, not
# as an argument, so it does not show up in `ps` or in the CI logs.
export DATABASE_URL="$(terraform output -raw db_connection_string)"
./publish.shAnd consumption from another module, which is the other big destination for outputs:
# In EcoMarket's root module
module "database" {
source = "./modules/database"
prefix = local.prefix
config = local.current
tags = local.common_tags
}
# A child module's outputs are read as module.<name>.<output>
locals {
db_endpoint = module.database.endpoint
}
output "db_endpoint" {
description = "PostgreSQL endpoint, re-exported from the module."
value = module.database.endpoint
}One concept is worth settling here: outputs are a module's public contract. What you do not publish, the consumer cannot use; what you do publish, you will have to maintain. Module design and passing variables between modules is the whole of module 4. And if you need to read the outputs of a different configuration, with its own state, the tool is terraform_remote_state, studied in Remote State.
- EcoMarket's
variables.tf / outputs.tf pattern
variables.tf / outputs.tf patternLet us put it all together in the definitive structure the ecomarket-infra repository will use.
# variables.tf
# ---------------------------------------------------------------------------
# Project identity
# ---------------------------------------------------------------------------
variable "project" {
description = "Short name of the project. It prefixes every resource."
type = string
default = "ecomarket"
nullable = false
validation {
condition = can(regex("^[a-z][a-z0-9-]{2,20}$", var.project))
error_message = "The project name must be lower case, start with a letter and be between 3 and 21 characters long."
}
}
variable "environment" {
description = "Environment to deploy. It must exist as a key in var.environments."
type = string
nullable = false
}
variable "region" {
description = "Deployment region. EcoMarket operates in Europe only."
type = string
default = "eu-west-1"
nullable = false
validation {
condition = startswith(var.region, "eu-")
error_message = "Under the data residency policy, the region must start with 'eu-'."
}
}
variable "contact" {
description = "Mailbox of the owning team, used in tags and alerts."
type = string
default = "[email protected]"
}
# ---------------------------------------------------------------------------
# Environment catalogue
# ---------------------------------------------------------------------------
variable "environments" {
description = "Definition of each EcoMarket environment, indexed by name."
type = map(object({
web_instances = number
web_class = optional(string, "t3.micro")
db_class = optional(string, "db.t3.micro")
retention_days = optional(number, 7)
multi_az = optional(bool, false)
protect_deletion = optional(bool, false)
extra_tags = optional(map(string), {})
}))
validation {
condition = contains(keys(var.environments), var.environment)
error_message = "Environment '${var.environment}' is not defined. Available: ${join(", ", keys(var.environments))}."
}
validation {
condition = alltrue([
for name, e in var.environments : e.web_instances >= 1 && e.web_instances <= 10
])
error_message = "Every environment must declare between 1 and 10 web instances."
}
}
# ---------------------------------------------------------------------------
# Database
# ---------------------------------------------------------------------------
variable "db_config" {
description = "Parameters of EcoMarket's PostgreSQL engine."
type = object({
engine = string
version = string
port = optional(number, 5432)
storage_gb = optional(number, 20)
})
default = {
engine = "postgres"
version = "16.3"
}
validation {
condition = var.db_config.engine == "postgres"
error_message = "EcoMarket only supports PostgreSQL."
}
}
variable "db_user" {
description = "PostgreSQL administrator user."
type = string
default = "ecomarket_admin"
}
variable "db_password" {
description = <<-EOT
The administrator's password. It is NEVER committed.
Pass it with TF_VAR_db_password from the team's secrets manager.
EOT
type = string
sensitive = true
nullable = false
validation {
condition = length(var.db_password) >= 16
error_message = "The password must be at least 16 characters long."
}
}And the matching outputs:
# outputs.tf
output "name_prefix" {
description = "The environment's name prefix, in the format ecomarket-<environment>."
value = local.prefix
}
output "environment_config" {
description = "Effective configuration of the environment, with the optional() values already resolved."
value = local.current
}
output "common_tags" {
description = "Tags that every resource in the environment must carry."
value = local.common_tags
}
output "endpoints" {
description = "The platform's entry points for the application team."
value = {
web = "https://${local.prefix}.ecomarket.example.com"
environment = var.environment
region = var.region
}
}
output "db_connection_string" {
description = "Connection string to PostgreSQL. It contains credentials."
value = "postgresql://${var.db_user}:${var.db_password}@${local.prefix}-db:${var.db_config.port}/ecomarket"
sensitive = true
}A complete run, with the secret kept out of the code:
# The password comes from the secrets manager, not from a file.
$ export TF_VAR_db_password="$(pass show ecomarket/dev/postgres)"
$ terraform plan -var-file=dev.tfvars -out=dev.tfplan
...
Plan: 3 to add, 0 to change, 0 to destroy.
Changes to Outputs:
+ db_connection_string = (sensitive value)
+ endpoints = {
+ environment = "dev"
+ region = "eu-west-1"
+ web = "https://ecomarket-dev.ecomarket.example.com"
}
+ name_prefix = "ecomarket-dev"Common Mistakes and Tips
- Believing that
TF_VAR_*takes priority over files. It is the other way round: it only beats thedefault. If your environment variable "does not work", look for a forgottenterraform.tfvarsin the directory. - Declaring a variable in
terraform.tfvars. That file only assigns; the declaration goes invariables.tf. Assigning a value to an undeclared variable producesValue for undeclared variable(a warning in the root, an error in a module). - Using
type = anyout of convenience. It switches off the checks and moves the error toapply, by which point you have already started creating things. - Confusing
optional(number, 5432)withdefault.optional()exists only inside anobjectand sets the value per attribute;defaultbelongs to the wholevariableblock. - Thinking
sensitive = trueencrypts something. It encrypts nothing: it only hides the value in the terminal output. The state and the plan file are still in plain text. - Passing secrets with
-var="password=...". They stay in the shell history and in the CI logs. UseTF_VAR_*from a secrets manager. - Committing a
.tfvarsfile with credentials. It is the most common way of leaking a secret into a repository. Add the secret files to.gitignorebefore the first commit and run a scanner such asgitleaksin the pipeline. - A useless
error_message. "Invalid value" helps nobody. State what was expected, what arrived and, where relevant, the list of accepted values. - Using
regex()withoutcan()in a condition.regex()raises an error when there is no match, and the user gets an internal failure instead of your message. Always wrap it. - Forgetting to double the backslashes in regular expressions. Inside an HCL string,
\dis\\d. A pattern that "never matches" is usually this. - One output per attribute. Ten loose outputs age worse than a single
endpointsoutput with an object inside. Group what is consumed together. - Tip: run
terraform console -var-file=prod.tfvarsand evaluatevar.environments[var.environment]before planning. You will see at a glance which effective values the deployment will get, with theoptional()entries already resolved. - Tip: generate the documentation for your variables and outputs automatically with
terraform-docs markdown . > README.md. If thedescriptionfields are well written, the README comes for free.
Exercises
Exercise 1: the environments variable with validations
Create an exercise-variables directory from scratch with a runnable configuration (the local and random providers) that:
- Declares
var.project,var.environmentand anenvironmentsvariable of typemap(object(...))with the attributesweb_instances(mandatory),db_class(optional, defaulting to"db.t3.micro") andretention_days(optional, defaulting to7). - Validates that
var.environmentexists as a key ofvar.environments. - Validates that every environment declares between 1 and 10 instances.
- Generates a
local_filewith the JSON of the selected environment's effective configuration. - Check what happens when you run
terraform plan -var="environment=qa"and when you declare an environment withweb_instances = 0.
Exercise 2: demonstrating precedence
Using the configuration from the previous exercise, demonstrate the precedence order empirically:
- Create
terraform.tfvarswithenvironment = "staging",a-common.auto.tfvarswithenvironment = "dev"andb-team.auto.tfvarswithenvironment = "prod". - Predict the value of
var.environmentin these four cases and check each one withterraform console:- with no flags at all;
- with
TF_VAR_environment=dev; - with
-var-file=production.tfvars(containingenvironment = "prod"); - with
-var="environment=staging" -var-file=production.tfvars.
- Explain which of the four results is the most surprising and why.
Exercise 3: secrets and sensitive outputs
Extend the configuration with the handling of the PostgreSQL password:
- Declare
var.db_passwordassensitive, with nodefault,nullable = false, and with a validation for a minimum length of 16 characters and for containing at least one digit. - Generate a
local_filenamedecomarket-<environment>-credentials.jsonwith user, host, port and password, withfile_permission = "0600". - Publish a
db_connection_stringoutput marked as sensitive and another one,db_port, that is not. - Apply and answer: what does
terraform planshow of the file's content? What doesterraform.tfstateactually contain? What does that imply for the repository's.gitignore?
Solutions
Solution 1:
# variables.tf
variable "project" {
description = "Name of the project."
type = string
default = "ecomarket"
nullable = false
}
variable "environment" {
description = "Environment to deploy."
type = string
default = "dev"
nullable = false
}
variable "environments" {
description = "Catalogue of EcoMarket environments."
type = map(object({
web_instances = number
db_class = optional(string, "db.t3.micro")
retention_days = optional(number, 7)
}))
default = {
dev = { web_instances = 1 }
staging = { web_instances = 2, db_class = "db.t3.small", retention_days = 14 }
prod = { web_instances = 3, db_class = "db.t3.medium", retention_days = 30 }
}
validation {
condition = contains(keys(var.environments), var.environment)
error_message = "Environment '${var.environment}' does not exist. Available: ${join(", ", keys(var.environments))}."
}
validation {
# alltrue() over a for expression: the pattern for validating collections.
condition = alltrue([
for n, e in var.environments : e.web_instances >= 1 && e.web_instances <= 10
])
error_message = "Every environment must declare between 1 and 10 web instances."
}
}# main.tf
locals {
prefix = "${var.project}-${var.environment}"
current = var.environments[var.environment]
}
resource "local_file" "effective_config" {
filename = "${path.module}/${local.prefix}-config.json"
file_permission = "0644"
content = jsonencode({
project = var.project
environment = var.environment
# local.current already carries the optional() values resolved.
config = local.current
})
}Result of the checks in point 5:
$ terraform plan -var="environment=qa"
╷
│ Error: Invalid value for variable
│
│ on variables.tf line 17:
│ 17: variable "environments" {
│
│ Environment 'qa' does not exist. Available: dev, prod, staging.
╵And with a badly sized environment:
$ terraform plan -var='environments={dev={web_instances=0}}' -var="environment=dev"
╷
│ Error: Invalid value for variable
│
│ Every environment must declare between 1 and 10 web instances.
╵Notice that the second validation uses alltrue([for ...]): it is the pattern for validating every element of a collection, and it plugs straight into what you learnt about for expressions in the previous lesson.
Checking the resolved optional() values:
$ terraform console
> var.environments["dev"]
{
"db_class" = "db.t3.micro"
"retention_days" = 7
"web_instances" = 1
}Even though we only wrote web_instances in the default, the object arrives complete.
Solution 2:
Predictions and results:
| Case | Expected value | Reason |
|---|---|---|
| No flags | "prod" |
The .auto.tfvars files (level 4) beat terraform.tfvars (level 3), and among themselves the alphabetically last one wins: b-team after a-common |
TF_VAR_environment=dev |
"prod" |
TF_VAR_* is level 2: it loses against every file |
-var-file=production.tfvars |
"prod" |
Level 5, beats the automatic ones (and the value happens to match) |
-var="environment=staging" -var-file=production.tfvars |
"prod" |
The flags are processed in order: -var-file comes later and overrides the -var |
$ terraform console
> var.environment
"prod"
$ TF_VAR_environment=dev terraform console
> var.environment
"prod"
$ terraform console -var="environment=staging" -var-file=production.tfvars
> var.environment
"prod"The most surprising result is the second: the environment variable has no effect at all because there are .auto.tfvars files in the directory. It is the number one cause of "it comes out differently on my machine" when somebody has a local .auto.tfvars that is not in the repository. The fourth is surprising too: plenty of people assume -var always beats -var-file, but what rules is the order on the command line.
Solution 3:
# variables.tf
variable "db_user" {
description = "PostgreSQL administrator user."
type = string
default = "ecomarket_admin"
}
variable "db_password" {
description = "The administrator's password. Pass it through TF_VAR_db_password."
type = string
sensitive = true
nullable = false
# No default: it is mandatory on purpose.
validation {
condition = length(var.db_password) >= 16
error_message = "The password must be at least 16 characters long."
}
validation {
condition = can(regex("[0-9]", var.db_password))
error_message = "The password must contain at least one digit."
}
}# main.tf
resource "local_file" "credentials" {
filename = "${path.module}/${local.prefix}-credentials.json"
# 0600: only the owner can read it.
file_permission = "0600"
content = jsonencode({
user = var.db_user
host = "${local.prefix}-db.ecomarket.example.com"
port = 5432
password = var.db_password
})
}# outputs.tf
output "db_connection_string" {
description = "Full connection string. It contains the password."
value = "postgresql://${var.db_user}:${var.db_password}@${local.prefix}-db:5432/ecomarket"
sensitive = true
}
output "db_port" {
description = "PostgreSQL port. It is not sensitive data."
value = 5432
}The run and the answers:
$ export TF_VAR_db_password="Example-Fictitious-2024"
$ terraform apply -auto-approve
# local_file.credentials will be created
+ resource "local_file" "credentials" {
+ content = (sensitive value)
+ file_permission = "0600"
+ filename = "./ecomarket-dev-credentials.json"
}
Outputs:
db_connection_string = <sensitive>
db_port = 5432-
The plan hides the file's entire content (
(sensitive value)), not just the password: sensitivity propagates to the wholecontentargument. That is correct, although it is awkward when you want to review the rest of the JSON. -
The state holds it in plain text:
$ jq -r '.resources[] | select(.name=="credentials") | .instances[0].attributes.content' terraform.tfstate
{"host":"ecomarket-dev-db.ecomarket.example.com","password":"Example-Fictitious-2024","port":5432,"user":"ecomarket_admin"}- Implications for the repository:
terraform.tfstate,terraform.tfstate.backupand the*.tfplanfiles must be in.gitignorewithout exception, because they are as sensitive as the secret they contain. The generated file's permissions (0600) are a good additional practice, but they do not make up for a committed state. The real solution is a remote backend with encryption at rest and access control, which is exactly the subject of the next module.
If you tried to publish the connection string without sensitive = true, Terraform would refuse with the error Output refers to sensitive values, forcing you to declare your intent.
Conclusion
You now know how to design the complete interface of a Terraform configuration:
- The
variableblock acceptsdescription,type,default,nullable,sensitiveand severalvalidationblocks; a variable with nodefaultis mandatory and in CI must be combined with-input=false. - Complex types (
object,map(object(...))) let you describe EcoMarket's whole environment catalogue in a single variable, andoptional(type, value)fills in the missing attributes so that your code does not have to check them. - There are six sources of values with a strict precedence:
default<TF_VAR_*<terraform.tfvars<*.auto.tfvars(alphabetical) <-var-file<-var, with the last two resolved in command-line order. sensitive = truehides values in the terminal and propagates automatically, but it does not encrypt the state or the plan file: real protection arrives with an encrypted backend.validationblocks turn business rules into clear errors before any infrastructure is touched;can(),try()andregex()make them robust, and since Terraform 1.9 they can span several variables.- The
outputblock publishes values withdescription,sensitiveand, exceptionally,depends_on; Terraform stops you exposing sensitive data without declaring it. - Outputs are consumed with
terraform output -raw/-jsonfrom scripts and asmodule.<name>.<output>from other configurations.
With the interface defined, the natural next step is what sits in between: the resources that interface configures. In the next lesson, Resource and Data Blocks, we will squeeze the resource block dry — the count and for_each meta-arguments, with the comparison table and the famous index-shifting problem; depends_on when it is unavoidable; and the complete lifecycle block with create_before_destroy, prevent_destroy, ignore_changes and replace_triggered_by — and we will learn to read existing infrastructure with the data block, which is Terraform's doorway into the world it does not manage.
