Using Input Variables in Terraform (With Examples)
Using input variables in Terraform is one of the first skills you should learn when building reusable Infrastructure as Code (IaC).
If you've ever copied the same Terraform configuration for development, staging, and production environments and only changed a few values, input variables solve that problem. Instead of hardcoding values throughout your configuration, you can define them once and supply different values whenever needed.
Whether you're deploying local resources or cloud infrastructure, input variables make Terraform configurations easier to maintain, reuse, and scale.
Why Using Input Variables in Terraform Is a Best Practice
Hardcoding values may work for quick testing, but it becomes difficult to manage as infrastructure grows.
Imagine deploying the same application across multiple environments. Without variables, you would need separate Terraform configurations for each environment. With variables, a single configuration can be reused everywhere.
Using input variables in Terraform helps you:
- Reuse the same code across development, testing, staging, and production environments.
- Reduce duplication and improve maintainability.
- Keep infrastructure configurations flexible.
- Simplify collaboration between team members.
- Make Terraform modules reusable.
If you're new to variables, you may also want to read our guide on Terraform Variable Block to understand all supported variable arguments.
How to Define Input Variables in Terraform
Input variables are typically declared inside a variables.tf file.
Here's a simple example:
variable "filename" {
description = "Name of the file to create"
default = "/root/pets.txt"
}
variable "file_content" {
description = "Text content inside the file"
default = "We love pets."
}
Each variable block starts with the variable keyword followed by a unique variable name.
Terraform supports several optional arguments, including:
descriptiontypedefaultvalidationsensitivenullable
The official Terraform documentation recommends defining variable types whenever possible because it helps Terraform detect invalid values early.
You can learn more about Terraform language features in the official Terraform Language Documentation.
How to Reference Input Variables in Terraform Resources
Once a variable is declared, it can be referenced anywhere within the configuration using the var.<variable_name> syntax.
resource "local_file" "pet_file" {
filename = var.filename
content = var.file_content
}
Terraform automatically replaces the variable references with the actual values supplied during execution.
This approach keeps resource definitions clean while separating infrastructure logic from configuration values.
Variable Types in Terraform
Terraform supports several variable types that help enforce data validation.
String
variable "environment" {
type = string
default = "dev"
}
Number
variable "instance_count" {
type = number
default = 2
}
Boolean
variable "enable_monitoring" {
type = bool
default = true
}
List
variable "availability_zones" {
type = list(string)
default = [
"us-east-1a",
"us-east-1b"
]
}
Map
variable "tags" {
type = map(string)
default = {
Environment = "Dev"
Team = "Platform"
}
}
Object
variable "server_config" {
type = object({
instance_type = string
volume_size = number
})
}
Using explicit variable types helps Terraform catch configuration mistakes before infrastructure changes are applied.
4 Ways to Pass Values to Input Variables in Terraform
Terraform supports multiple ways to assign values to variables.
1. Using Default Values
Default values are declared directly inside the variable block.
variable "instance_type" {
default = "t3.micro"
}
If no value is supplied elsewhere, Terraform uses the default.
2. Using Command-Line Variables
You can pass values directly during execution.
terraform apply -var="filename=/tmp/output.txt"
This method is useful for quick testing but can become difficult to manage in larger environments.
3. Using Variable Definition Files (.tfvars)
Create a file named terraform.tfvars or any custom .tfvars file.
filename = "/tmp/output.txt"
file_content = "Updated content here."
Apply the configuration:
terraform apply -var-file="custom.tfvars"
This is one of the most common approaches used in production environments.
4. Using Environment Variables
Terraform can automatically read environment variables.
export TF_VAR_environment=production
export TF_VAR_instance_type=t3.medium
This approach is commonly used in CI/CD pipelines.
Pro Tip
Avoid storing secrets such as database passwords, API keys, or tokens directly inside .tfvars files committed to source control.
Instead, use:
- Environment variables
- AWS Secrets Manager
- HashiCorp Vault
- Azure Key Vault
- Google Secret Manager
Understanding Variable Precedence in Terraform
When the same variable is defined in multiple locations, Terraform follows a precedence order.
Generally, more specific inputs override less specific ones.
The most common order is:
- Command-line
-var - Command-line
-var-file - Auto-loaded
.tfvarsfiles - Environment variables (
TF_VAR_*) - Default values in variable blocks
Understanding precedence helps avoid unexpected values during deployments.
Updating Resources with Variables
One of the biggest advantages of using input variables in Terraform is that infrastructure updates become predictable.
For example, if you modify the value of file_content, Terraform detects the change during the planning phase and shows exactly what will happen before any resources are updated.
This makes infrastructure changes safer and easier to review.
Before applying changes, always run:
terraform plan
You can learn more about reviewing changes in our guide on Terraform Commands Explained.
Managing Multiple Resources with Variables
Variables become even more valuable when multiple resources share common configuration values.
Instead of repeating values throughout your codebase, define them once and reuse them.
variable "prefix" {
default = "pet"
}
resource "random_pet" "my_pet" {
prefix = var.prefix
separator = "-"
length = 2
}
In real-world projects, variables are commonly used for:
- Naming conventions
- Tags
- Environment names
- AWS regions
- Instance sizes
- Networking settings
Variables become even more powerful when combined with Creating and Using Modules in Terraform, allowing reusable infrastructure components to accept different inputs across environments.
You may also find these related guides useful:
- Modules in Terraform
- Meta Arguments in Terraform
- For Each Meta Arguments in Terraform
- Count Meta Arguments in Terraform
Real-World Example: AWS EC2 with Input Variables
Input variables are heavily used in cloud infrastructure deployments.
Here's a simple AWS EC2 example:
variable "ami_id" {
description = "AMI ID for the EC2 instance"
default = "ami-xxxxxxxx"
}
variable "instance_type" {
description = "EC2 instance type"
default = "t3.micro"
}
resource "aws_instance" "web_server" {
ami = var.ami_id
instance_type = var.instance_type
}
In production environments, teams commonly expose the following values as variables:
- AMI IDs
- Instance types
- VPC IDs
- Subnet IDs
- Security Group IDs
- Tags
- Environment names
This allows the same Terraform codebase to be deployed across multiple AWS accounts and environments without modifying the resource definitions.
If you're deploying AWS resources, these guides may help:
- Getting Started with Terraform on AWS
- AWS EC2 with Terraform
- AWS S3 with Terraform
- AWS IAM with Terraform
You can also explore reusable Terraform modules through the official Terraform Registry.
Common Mistakes to Avoid When Using Input Variables in Terraform
Many beginners make the same mistakes when working with variables.
Avoid these issues:
- Hardcoding values instead of using variables.
- Omitting variable types.
- Storing secrets in Git repositories.
- Using unclear variable names.
- Creating too many unnecessary variables.
- Ignoring variable validation rules.
Well-designed variables improve readability and make Terraform configurations easier to maintain.
Conclusion
Using input variables in Terraform allows you to build flexible, reusable, and maintainable infrastructure configurations.
They help separate configuration values from resource logic, support multi-environment deployments, and improve collaboration across teams.
As your Terraform projects grow, variables become a foundational building block for creating scalable infrastructure and reusable modules.
Frequently Asked Questions (FAQs)
What is the use of input variables in Terraform?
Input variables allow values to be passed into Terraform configurations, making infrastructure code reusable and easier to maintain.
How do I pass variables in Terraform?
You can pass variables using:
- Default values
- Command-line
-var .tfvarsfiles- Environment variables
- Terraform Cloud workspace variables
Can I override default variable values?
Yes. Values provided through command-line arguments, .tfvars files, or environment variables can override default values.
Are input variables required in Terraform?
No. Variables are optional, but they are considered a best practice for building reusable and maintainable Terraform configurations.
What is the difference between input variables and output variables?
Input variables provide values to Terraform configurations, while output variables expose values from Terraform resources after deployment.
For a deeper comparison, see our guide on Output Variables in Terraform.
What are variable types in Terraform?
Terraform supports several variable types including:
- string
- number
- bool
- list
- map
- object
Using types improves validation and helps prevent configuration errors.
What is variable precedence in Terraform?
Variable precedence determines which value Terraform uses when the same variable is defined in multiple locations. Command-line values typically take precedence over defaults.
8 free, 100% client-side tools for developers — no signup, no data uploads.
Explore all tools