🎓 A1Learner
🔍
0 of 50 lessons completed

Variables

A variable is a named value that a configuration can reuse. One variable can change a result without editing every line that uses it.

One variable block

The label names the variable. The type and default describe its value.

variable "greeting" {
  type    = string
  default = "Hello from Terraform."
}

Use the variable

The var. prefix reads the value. The resource uses it in place of a fixed string.

content = var.greeting

Change it for one run

The -var flag sets a value for that run only. The file itself stays unchanged.

terraform plan -var="greeting=Hello again."

Example

# main.tf
terraform {
  required_providers {
    local = {
      source  = "hashicorp/local"
      version = "2.9.1"
    }
  }
}

variable "greeting" {
  type    = string
  default = "Hello from Terraform."
}

resource "local_file" "hello" {
  filename = "hello.txt"
  content  = var.greeting
}

# Commands:
# terraform init
# terraform plan
# terraform apply
# terraform destroy

Key points

  • A variable block declares a value the configuration can use.
  • The type sets what kind of value it holds, such as a string or a number.
  • A default sets the value used when no other value is given.
  • A variable is read with the var. prefix, such as var.greeting.
  • Change the variable once, and every place that uses it changes.
  • A value can also be set on the command line with -var, which beats the default.

The variable holds the greeting text. The resource reads it with var.greeting. Change the variable, and the plan shows the file content changing. Destroy removes the file after practice.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

How do you read a variable called greeting inside a configuration?