Variable Files and .tfvars
A variable file is a file that holds values for the variables in a configuration. It keeps values apart from code, so one configuration can serve many environments.
terraform.tfvars loads by itself
This file sits beside the configuration. Terraform picks it up with no flag.
environment = "staging"Load a named file
Use -var-file for any file with a different name.
terraform plan -var-file="prod.tfvars"Override one value
The -var flag wins over the file. It is handy for a single change.
terraform apply -var="environment=prod"Example
# main.tf
terraform {
required_providers {
local = {
source = "hashicorp/local"
version = "~> 2.0"
}
}
}
variable "environment" {
type = string
default = "dev"
}
resource "local_file" "hello" {
content = "Hello from the ${var.environment} environment."
filename = "${path.module}/hello-${var.environment}.txt"
}
# terraform.tfvars
environment = "staging"
# prod.tfvars
environment = "prod"
# commands
terraform init
terraform apply -auto-approve
cat hello-staging.txtKey points
- A file named terraform.tfvars loads by itself. Terraform reads it on every run.
- A file with any other name needs the -var-file flag. The flag names the file to load.
- The -var flag sets one value on the command line. It beats any value in a file.
- Values in a file are plain assignments. Each line names a variable and gives it a value.
- One file per environment is a common pattern. Dev, staging, and prod each get their own file.
The value staging comes from terraform.tfvars, not from the code. The same configuration would write a different file for dev. Change the file, not the code, to change the environment.
Note
a .tfvars file that is committed is no place for a real secret.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
Which file does Terraform load by itself, with no flag?