This example shows how to keep Terraform variable values in a custom file such as anyotherfile.tfvars and load it with terraform apply -var-file="anyotherfile.tfvars". Unlike terraform.tfvars, a file with any other name is not loaded automatically, so you must pass it on the command line every time you run plan, apply or destroy.
The example code in plain text
The embedded gist above contains two files. Here they are as plain text so you can copy them:
anyotherfile.tfvars
reponame = "terraform-var-anyotherfile-tfvars"Code language: JavaScript (javascript)
main.tf (as written in the original example)
provider "github" {
token = ""
organization = "devopsschool-sample-projects"
}
variable reponame {}
resource "github_repository" "example" {
name = "${var.reponame}"
description = "My awesome codebase"
private = false
}Code language: PHP (php)
How the example works
variable reponame {}declares an input variable with no default value, so Terraform must get a value for it from somewhere before it can plan.anyotherfile.tfvarsassigns that value. A.tfvarsfile contains only variable assignments, never resources.- The
github_repositoryresource reads the value throughvar.reponameand creates a public repository with that name. -var-file="anyotherfile.tfvars"tells Terraform to read the file. Without it, Terraform stops with “No value for required variable” (or asks for the value interactively).
Run it step by step
# 1. Give the GitHub provider a token (never hard-code it in .tf files)
export GITHUB_TOKEN="<your-personal-access-token>"
# 2. Download the provider
terraform init
# 3. Preview the change using the custom variable file
terraform plan -var-file="anyotherfile.tfvars"
# 4. Create the repository
terraform apply -var-file="anyotherfile.tfvars"
# 5. Clean up when you are done (pass the same file again)
terraform destroy -var-file="anyotherfile.tfvars"Code language: PHP (php)
The token needs permission to create repositories in the organization (for a classic token, the repo scope).
Updated syntax for Terraform 0.13 and later
The original example uses Terraform 0.11 style. It still explains the idea, but on current Terraform versions write it like this:
terraform {
required_providers {
github = {
source = "integrations/github"
}
}
}
provider "github" {
owner = "devopsschool-sample-projects"
# The token is read from the GITHUB_TOKEN environment variable
}
variable "reponame" {
description = "Name of the GitHub repository to create"
type = string
}
resource "github_repository" "example" {
name = var.reponame
description = "My awesome codebase"
visibility = "public"
}Code language: PHP (php)
- Variable names are quoted and should have a
typeanddescription. - Use
var.reponamedirectly; the"${...}"wrapper is only needed inside longer strings. - The GitHub provider now lives at
integrations/github;ownerreplacesorganization, andvisibilityreplaces the deprecatedprivateargument.
Where Terraform looks for variable values
When the same variable is set in several places, Terraform uses this order. Later sources override earlier ones:
- Environment variables named
TF_VAR_<name>, for exampleTF_VAR_reponame - The
terraform.tfvarsfile, if present - The
terraform.tfvars.jsonfile, if present - Any
*.auto.tfvarsor*.auto.tfvars.jsonfiles, in alphabetical order -varand-var-fileoptions on the command line, in the order you type them
A default in the variable block is used only when none of these provide a value.
One variable file per environment
The most common real-world use of -var-file is keeping one file per environment while the code stays the same:
# dev.tfvars
reponame = "myapp-dev"
# prod.tfvars
reponame = "myapp-prod"
terraform plan -var-file="dev.tfvars"
terraform plan -var-file="prod.tfvars"Code language: PHP (php)
Use a separate state for each environment (separate backends, directories or workspaces), otherwise applying prod.tfvars would modify the resources created with dev.tfvars.
Common errors and fixes
| Error | Cause | Fix |
|---|---|---|
| No value for required variable | The .tfvars file was not passed, or the variable name in the file is misspelled | Add -var-file=... and check the name matches the variable block |
| Given variables file … does not exist | The path is relative to the directory where you run Terraform | Run from the right folder or give the full path |
| Value for undeclared variable | The file sets a variable that no variable block declares | Declare the variable or remove the line from the file |
| 401 Bad credentials | Missing, expired or under-privileged GitHub token | Export a valid GITHUB_TOKEN with repository permissions |
| Repository creation failed: name already exists | A repository with that name already exists | Change reponame or import the existing repository |
Best practices
- Never put secrets such as tokens or passwords in
.tfvarsfiles that are committed to Git. Use environment variables or a secret manager, and mark sensitive variables withsensitive = true. - Add
*.tfvarsfiles that contain secrets to.gitignore; keep non-secret environment files in version control so runs are reproducible. - Give every variable a
type, adescriptionand, where useful, avalidationblock. - Pin the provider version you have tested and commit
.terraform.lock.hcl.
Frequently asked questions
Is anyotherfile.tfvars loaded automatically?
No. Terraform only loads terraform.tfvars, terraform.tfvars.json and files ending in .auto.tfvars or .auto.tfvars.json automatically. Any other name must be passed with -var-file.
Can I pass more than one -var-file?
Yes. Repeat the option, for example -var-file=common.tfvars -var-file=prod.tfvars. If both set the same variable, the file given last wins.
What is the difference between -var and -var-file?
-var sets one value directly, such as -var="reponame=demo". -var-file loads many values from a file. Both have the same priority; whichever appears later on the command line wins.
Can a .tfvars file use expressions or other variables?
No. Values in .tfvars files must be literal values: strings, numbers, booleans, lists and maps. Put calculations in locals inside your configuration instead.
Related tutorials
- Terraform Variables and Configuration explained
- Terraform Environment Variables Explained
- HCP Terraform: Variables, Scope & Precedence
- All Terraform tutorials
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services — all in one place.
Explore Hospitals