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

Variables with types and defaults
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):

  1. The default in the declaration
  2. terraform.tfvars and *.auto.tfvars files
  3. -var-file=prod.tfvars on the command line
  4. -var="region=eu-west-1" on the command line
  5. Environment variables named TF_VAR_<name> (these come before files, after defaults)
# prod.tfvars
environment    = "prod"
instance_count = 3

Validation

Validate allowed values
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?

  1. region
  2. var.region
  3. variable.region
  4. ${region}
Show answer

Answer: var.region