Terraform Tutorial · Terraform Basics · Lesson 6 of 25
Terraform Variables
Input variables make configurations reusable. Learn to declare variables with types, defaults, descriptions, validation and sensitive values, and how to set them.
Declaring variables
variable "environment" {
description = "Deployment environment"
type = string
default = "dev"
}
variable "instance_count" {
type = number
default = 2
}
variable "tags" {
type = map(string)
default = { team = "web" }
}
output "summary" {
value = "${var.instance_count} instances in ${var.environment} for team ${var.tags.team}"
}
Output
summary = "2 instances in dev for team web"
Run this on your computer — see “Get Started” for setup.
Refer to a variable as var.<name>.
Setting values
In order of precedence (later wins):
- The
defaultin the declaration terraform.tfvarsand*.auto.tfvarsfiles-var-file=prod.tfvarson the command line-var="region=eu-west-1"on the command line- Environment variables named
TF_VAR_<name>(these come before files, after defaults)
# prod.tfvars
environment = "prod"
instance_count = 3
Validation
variable "environment" {
type = string
default = "staging"
validation {
condition = contains(["dev", "staging", "prod"], var.environment)
error_message = "environment must be dev, staging or prod."
}
}
output "environment" {
value = var.environment
}
Output
environment = "staging"
Run this on your computer — see “Get Started” for setup.
Sensitive values
Mark secrets sensitive = true so Terraform hides them in plans and output. They are still stored in the state,
so protect the state file. Since Terraform 1.10, ephemeral = true variables are never written to state or plan
files at all.
Test yourself
How do you refer to a variable named region?
regionvar.regionvariable.region${region}
Show answer
Answer: var.region