Using Variables in Terraform: 5 Methods Explained

Published: 2025-08-05
7 min read
Share:

Hardcoding values inside Terraform configurations might work for small experiments, but it quickly becomes difficult to manage when you need separate development, staging, and production environments.

Using variables in Terraform allows you to reuse the same code with different inputs, making your infrastructure more flexible, maintainable, and scalable. Whether you're deploying AWS resources, creating reusable modules, or automating infrastructure through CI/CD pipelines, Terraform variables are a fundamental concept you need to understand.

In this guide, you'll learn every supported way to provide variable values in Terraform, how Terraform decides which value takes precedence, and the best practices used in real-world Terraform projects.

Before proceeding, make sure you're familiar with Terraform basics and the structure of a Terraform variable block.

What Are Variables in Terraform and Why Do They Matter?

Variables in Terraform act as placeholders for dynamic input values.

Instead of hardcoding values directly into your .tf files, you can define variables and provide different values during deployment. This makes your configurations reusable across environments and easier to maintain.

A basic variable declaration looks like this:

variable "instance_type" {
  description = "EC2 instance type"
  type        = string
}

If a variable does not have a default value, Terraform requires you to provide one before applying the configuration.

To understand the complete structure and available arguments, refer to this guide on the Terraform variable block.

Method 1: Provide Variables Interactively During Terraform Apply

If Terraform cannot find a value for a required variable, it prompts you to enter one manually.

variable "environment" {}

When you run:

terraform apply

Terraform prompts:

var.environment
  Enter a value:

This approach is useful for testing and learning Terraform, but it is not suitable for automation because it requires manual input.

If you're new to variables, you may also want to learn how input variables in Terraform work throughout a configuration.

Method 2: Pass Variables Using the -var Command Line Flag

Terraform allows you to pass variables directly through the command line using the -var option.

terraform apply \
-var="instance_type=t3.micro" \
-var="environment=dev"

You can specify multiple variables by repeating the -var flag.

This method is useful for:

  • Quick testing
  • Temporary overrides
  • Automation scripts
  • Running environment-specific deployments

Be careful when using this method for sensitive values because command-line arguments may be visible in shell history or process listings.

Method 3: Set Terraform Variables Through Environment Variables

Terraform automatically reads environment variables that start with the TF_VAR_ prefix.

For example:

export TF_VAR_instance_type="t3.micro"
export TF_VAR_environment="dev"

Now run:

terraform apply

Terraform automatically loads these values.

Environment variables are commonly used in:

  • GitHub Actions
  • GitLab CI/CD
  • Jenkins pipelines
  • Azure DevOps pipelines

Pro Tip

Environment variables are often preferred for sensitive values because they allow credentials and secrets to be injected securely at runtime instead of storing them in Terraform configuration files.

For managing secrets, consider integrating Terraform with services such as AWS Secrets Manager or HashiCorp Vault.

Method 4: Use Variable Definition Files (.tfvars and .tfvars.json)

Variable definition files help separate configuration data from infrastructure code.

This is one of the most common approaches used in production environments.

Example: terraform.tfvars

instance_type = "t3.micro"
environment   = "dev"

Example: variables.auto.tfvars

instance_type = "t3.small"
environment   = "staging"

Terraform automatically loads:

  • terraform.tfvars
  • terraform.tfvars.json
  • *.auto.tfvars
  • *.auto.tfvars.json

Using tfvars files makes it easier to maintain different configurations for development, staging, and production environments.

Method 5: Pass Custom Variable Files with -var-file

If your variable file uses a custom name, Terraform will not automatically load it.

You can specify it manually using -var-file.

terraform apply -var-file="prod.tfvars"

You can also maintain multiple environment-specific files:

dev.tfvars
staging.tfvars
prod.tfvars

Then choose the appropriate file during deployment.

terraform apply -var-file="prod.tfvars"

This approach is widely used when managing multiple environments from a single Terraform codebase.

Quick Comparison of Terraform Variable Input Methods

Each method serves a different purpose:

  • Interactive prompts are useful for learning and testing.
  • -var flags work well for quick overrides.
  • Environment variables are ideal for CI/CD pipelines and sensitive values.
  • terraform.tfvars files are commonly used for environment-specific settings.
  • -var-file is best when managing multiple environments with separate configuration files.

Most production Terraform repositories rely on tfvars files for environment configuration and use environment variables for secrets.

Terraform Variable Precedence: Which Value Wins?

Terraform follows a defined order of precedence when the same variable is assigned from multiple sources.

According to the official Terraform documentation, higher-precedence values override lower-precedence values.

The precedence order is:

  1. Environment variables (TF_VAR_name)
  2. terraform.tfvars and terraform.tfvars.json
  3. *.auto.tfvars and *.auto.tfvars.json
  4. Command-line options (-var and -var-file)

The highest-precedence source wins.

Example

Assume the variable instance_type is defined in several locations:

export TF_VAR_instance_type="t3.nano"
# terraform.tfvars
instance_type = "t3.micro"
# production.auto.tfvars
instance_type = "t3.small"
terraform apply -var="instance_type=t3.medium"

Terraform uses:

t3.medium

because the command-line argument has the highest precedence.

Common Mistake

Many engineers spend time troubleshooting unexpected Terraform behavior without realizing that a CLI -var argument is overriding values defined in tfvars files.

Whenever a variable value looks incorrect, check the highest-precedence source first.

Best Practices for Using Variables in Terraform

Following a few simple practices can make Terraform configurations easier to maintain and reuse.

Use Clear and Descriptive Variable Names

Good variable names make configurations easier to understand.

Prefer:

variable "instance_type" {}

Over:

variable "type" {}

Define Variable Types

Type constraints help Terraform catch invalid inputs early.

variable "instance_count" {
  type = number
}

Terraform supports:

  • string
  • number
  • bool
  • list
  • set
  • map
  • tuple
  • object

Add Descriptions to Every Variable

Descriptions improve readability and help teams understand the purpose of each variable.

variable "environment" {
  description = "Deployment environment"
}

Avoid Hardcoding Secrets

Never store passwords, API keys, or credentials directly in Terraform code.

Instead, use:

  • Environment variables
  • AWS Secrets Manager
  • HashiCorp Vault
  • Secure CI/CD secret stores

Keep Variables in a Dedicated File

Most Terraform projects organize variable declarations inside a dedicated:

variables.tf

file.

This makes large configurations easier to navigate.

Design Variables for Reusable Modules

Variables become even more important when building reusable Terraform modules.

Well-designed module inputs make your infrastructure easier to share and maintain across teams.

After mastering variables, continue with these Terraform topics:

Conclusion

In real-world Terraform projects, variables are what make configurations reusable across environments and teams.

Understanding where variable values come from and how precedence works helps prevent configuration mistakes that can be difficult to troubleshoot later. Once you're comfortable using variables in Terraform, you'll be able to build cleaner configurations, create reusable modules, and manage infrastructure at scale with greater confidence.

Frequently Asked Questions (FAQs)

What is the best way to pass variables in Terraform?

For most production environments, tfvars files are used for environment-specific configuration, while environment variables are used for sensitive values and CI/CD integrations.

What happens if multiple sources define the same variable?

Terraform follows a precedence hierarchy. Higher-precedence sources override lower-precedence sources, with command-line arguments having the highest priority.

Are Terraform variables limited to strings?

No. Terraform supports multiple data types, including strings, numbers, booleans, lists, maps, sets, tuples, and objects.

Can Terraform variables store secrets?

Yes, but sensitive values should not be hardcoded. Use environment variables, secret management services, or secure CI/CD platforms instead.

What is the purpose of .auto.tfvars files?

Terraform automatically loads .auto.tfvars files during execution, allowing you to provide variable values without explicitly referencing the file.

Where can I find official Terraform providers and modules?

The official Terraform Registry contains verified providers, modules, and documentation maintained by HashiCorp and the community.

Free Engineering ToolsNEW

8 free, 100% client-side tools for developers — no signup, no data uploads.

Explore all tools