Course contentsShow
← Cloud and Infrastructure
Lesson 760 of 2,98914. Terraform FundamentalsFree lesson

Passing Variables: CLI and tfvars Files

Supply variable values using command-line flags and .tfvars files.

Passing Variables: CLI and tfvars Files

What you'll learn: How to supply values to your Terraform variables from the command line and special .tfvars files instead of hardcoding them.

You've declared variables with types and validation rules—now you need to set their values. Terraform offers flexible ways to provide these values without editing your main configuration files.

Command-Line Flags

Pass values directly when running Terraform commands using the -var flag:

terraform apply -var="region=us-west-2" -var="instance_count=3"

This method works well for quick overrides or when automating with scripts. Each -var flag sets one variable.

tfvars Files

For more organized variable management, create .tfvars files that list variable assignments:

terraform.tfvars:

region         = "us-west-2"
instance_count = 3
environment    = "production"

Terraform automatically loads any file named terraform.tfvars or *.auto.tfvars. For other filenames, specify explicitly:

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

Think of it this way: Your variable declarations are like a form with blank fields, while CLI flags and .tfvars files are different ways to fill out that form—CLI is like writing values directly on the command, .tfvars is like having pre-filled template sheets for different scenarios (dev, staging, prod).

Which Method to Use?

  • CLI flags: One-off overrides, automation scripts, sensitive values
  • tfvars files: Environment-specific configurations, team collaboration, reusable value sets

You can combine both—CLI flags override values from .tfvars files, giving you flexibility when needed.

Key Takeaway: Use -var flags for quick value injection and .tfvars files for organized, reusable variable assignments across different environments.