MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Terraform variable using anyotherfile.tfvars example

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

  1. variable reponame {} declares an input variable with no default value, so Terraform must get a value for it from somewhere before it can plan.
  2. anyotherfile.tfvars assigns that value. A .tfvars file contains only variable assignments, never resources.
  3. The github_repository resource reads the value through var.reponame and creates a public repository with that name.
  4. -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 type and description.
  • Use var.reponame directly; the "${...}" wrapper is only needed inside longer strings.
  • The GitHub provider now lives at integrations/github; owner replaces organization, and visibility replaces the deprecated private argument.

Where Terraform looks for variable values

When the same variable is set in several places, Terraform uses this order. Later sources override earlier ones:

  1. Environment variables named TF_VAR_<name>, for example TF_VAR_reponame
  2. The terraform.tfvars file, if present
  3. The terraform.tfvars.json file, if present
  4. Any *.auto.tfvars or *.auto.tfvars.json files, in alphabetical order
  5. -var and -var-file options 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

ErrorCauseFix
No value for required variableThe .tfvars file was not passed, or the variable name in the file is misspelledAdd -var-file=... and check the name matches the variable block
Given variables file … does not existThe path is relative to the directory where you run TerraformRun from the right folder or give the full path
Value for undeclared variableThe file sets a variable that no variable block declaresDeclare the variable or remove the line from the file
401 Bad credentialsMissing, expired or under-privileged GitHub tokenExport a valid GITHUB_TOKEN with repository permissions
Repository creation failed: name already existsA repository with that name already existsChange reponame or import the existing repository

Best practices

  • Never put secrets such as tokens or passwords in .tfvars files that are committed to Git. Use environment variables or a secret manager, and mark sensitive variables with sensitive = true.
  • Add *.tfvars files that contain secrets to .gitignore; keep non-secret environment files in version control so runs are reproducible.
  • Give every variable a type, a description and, where useful, a validation block.
  • 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

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services — all in one place.

Explore Hospitals
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.

Related Posts

Terraform Variable Example: Azure & AWS

This page shows how to declare and use Terraform input variables of type number, string, bool, list and map with AWS and Azure resources. Below the original…

Read More

Terraform dynamaic block details explaination with example

A Terraform dynamic block generates repeated nested blocks inside a resource, data source, provider or provisioner, such as ingress rules in a security group or rule blocks…

Read More

Terraform Error Handing with Try Catch

Terraform has no try { } catch { } block. Error handling in HCL uses the try() function, which returns the first of its arguments that evaluates…

Read More

Terraform: Example Code for Create Multiple Azure Linux Vms

This page shows how to create several Azure Linux virtual machines from one Terraform configuration by using the count meta-argument. The VMs sit behind a load balancer…

Read More

Terraform Tools for Developer Productivity Master Guide

Tools, Workflow, Security, Testing, CI/CD, Automation, AI Assistance, Governance, and Production Best Practices Verified baseline: 5 September 2026Audience: Terraform developers, DevOps/SRE, platform/cloud engineers, module authors, DevSecOps teams, and engineering…

Read More

Terraform Conditional Expressions and Logic: Complete Guide with Examples

Terraform Conditional Expressions and Logic — Summary Table # Concept Purpose Example Creates Resources? 1 Ternary operator Choose between two values var.env == “prod” ? “t3.large” :…

Read More