Using Variables in Terraform – Best Methods Explained

Using variables in Terraform is a critical practice for anyone building scalable, reusable infrastructure as code. Variables make it easier to manage configurations, customize environments, and simplify collaboration across teams.

In this guide, you’ll discover various methods to pass values into variables, understand precedence rules, and get hands-on with different formats to suit both simple and complex deployments.

What Are Variables in Terraform?

Variables in Terraform are placeholders for dynamic input values. Instead of hardcoding every value in your .tf files, you can use variables to define reusable and flexible configurations.

These variables are declared in a variable block and can optionally include a default value. If the default isn’t provided, you must supply a value during runtime using one of the supported input methods.

1. Interactive Input During Terraform Apply

When a variable has no default value and no value is provided elsewhere, Terraform prompts the user to enter it manually during execution.

variable "filename" {}

On running terraform apply, you’ll be asked:

var.filename
Enter a value:

This method is suitable for quick, one-off configurations but is inefficient for automation.

2. Using the -var Command Line Flag

A more structured approach is to pass variable values through the CLI using the -var option.

terraform apply -var="filename=/root/pets.txt" -var="length=2"

You can include multiple variables by repeating the -var flag. This method provides control and is useful for scripting Terraform workflows.

3. Setting Environment Variables

Terraform can read values from environment variables if you prefix them with TF_VAR_.

export TF_VAR_filename="/root/pets.txt"
export TF_VAR_length=2

Environment variables are ideal for integrating Terraform into CI/CD pipelines or for developers who want to avoid storing secrets in code.

4. Variable Definition Files (.tfvars and .tfvars.json)

Variable values can also be stored in external files. These files are written in HCL or JSON formats and contain only the variable assignments.

Example: terraform.tfvars

filename = "/root/pets.txt"
length = 2

Example: variables.auto.tfvars

filename = "/root/mypet.txt"

These files allow you to separate code from configuration, making it easier to manage across environments like dev, staging, and prod.

5. Passing Variable Files with -var-file

If your variable file doesn’t use a standard name like terraform.tfvars or *.auto.tfvars, you can pass it explicitly:

terraform apply -var-file="custom-vars.tfvars"

This approach gives flexibility in naming and allows you to manage multiple environments or projects easily.

Variable Precedence in Terraform

When the same variable is defined in multiple locations, Terraform uses a specific order of precedence:

  1. Environment Variables (TF_VAR_name)
  2. terraform.tfvars or terraform.tfvars.json
  3. Files matching *.auto.tfvars or *.auto.tfvars.json (in lexical order)
  4. Command-line flags (-var or -var-file)

The last option takes the highest priority and overrides all others.

Example:

Assume the following values are set for the same variable filename:

  • TF_VAR_filename="/root/cats.txt"
  • terraform.tfvars contains "/root/pets.txt"
  • variable.auto.tfvars contains "/root/mypet.txt"
  • terraform apply -var="filename=/root/best-pet.txt"

Result: Terraform will use "/root/best-pet.txt" because CLI input has the highest precedence.

Best Practices for Using Variables in Terraform

  • Always use descriptive names for variables to make configuration readable.
  • Group variable declarations in a separate variables.tf file for better organization.
  • Avoid hardcoding sensitive values, especially secrets or credentials. Use environment variables or secret managers.
  • Document variables using the description argument.
  • Use type constraints to catch errors early and enforce input validation.

Conclusion

Using variables in Terraform is more than a convenience—it’s a best practice that helps you write clean, modular, and reusable code. Whether you’re deploying a single file or an entire cloud environment, knowing how to pass variable values and understanding their precedence can save you from configuration mistakes and headaches down the line.

Mastering the different ways to pass input—from CLI flags to environment variables and .tfvars files—empowers you to write Terraform code that scales with your infrastructure.

Frequently Asked Questions (FAQs)

1. What is the best way to pass variables in Terraform?

Using .tfvars files or environment variables is ideal for reusable and secure configuration, especially in automated pipelines.

2. What happens if multiple sources define the same variable?

Terraform uses a precedence hierarchy. CLI flags override all others, followed by auto.tfvars, terraform.tfvars, and then environment variables.

3. Are variable values required to be strings?

No. Terraform supports multiple types—string, number, bool, list, map, set, tuple, and object.

4. Can I use secrets in Terraform variables?

Yes, but avoid hardcoding them. Use environment variables or a secrets manager and reference them securely.

5. What is .auto.tfvars used for?

Terraform automatically loads all .auto.tfvars files in a directory, eliminating the need to specify them explicitly during execution.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top