How to Pass Variables to Terraform: Simple Guide
To pass a variable to
terraform, define it in a variable block in your configuration, then provide its value using a -var command-line option, a .tfvars file, or environment variables. This lets you customize your infrastructure without changing the code.Syntax
Define variables in Terraform using a variable block with a name and optional default value. Pass values when running Terraform with -var or -var-file. Variables can also be set via environment variables.
variable "name" {}: Declares a variable.-var 'name=value': Passes a variable value via CLI.-var-file=filename.tfvars: Loads variables from a file.- Environment variables: Use
TF_VAR_nameto set variables.
hcl
variable "region" { description = "AWS region to deploy" type = string default = "us-west-2" } # Passing variable via CLI: # terraform apply -var='region=us-east-1' # Passing variable via file: # terraform apply -var-file="custom.tfvars"
Example
This example shows how to define a variable for AWS region and pass its value using the command line.
hcl
variable "region" { description = "AWS region to deploy" type = string default = "us-west-2" } provider "aws" { region = var.region } resource "aws_s3_bucket" "example" { bucket = "my-example-bucket-12345" acl = "private" } # Run this with: # terraform init # terraform apply -var='region=us-east-1' -auto-approve
Output
aws_s3_bucket.example: Creating...
aws_s3_bucket.example: Creation complete after 2s [id=my-example-bucket-12345]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
Common Pitfalls
Common mistakes when passing variables include:
- Not defining the variable in the configuration before passing it.
- Using incorrect variable names or typos in
-varor.tfvarsfiles. - Forgetting to run
terraform initafter adding variables. - Passing sensitive data directly on the command line, which can be insecure.
Always verify variable names and prefer .tfvars files or environment variables for sensitive values.
hcl
/* Wrong: Passing undefined variable */ # terraform apply -var='region=us-east-1' /* Right: Define variable first */ variable "region" { type = string } # Then pass value as shown in previous examples
Quick Reference
| Method | How to Use | Notes |
|---|---|---|
| Variable Block | Define with variable "name" {} | Required to declare variables |
| CLI Option | Use -var 'name=value' | Overrides default or file values |
| Variable File | Use -var-file=filename.tfvars | Good for multiple variables |
| Environment Variable | Set TF_VAR_name=value | Useful for automation and secrets |
Key Takeaways
Declare variables in Terraform using the variable block before passing values.
Pass variable values via CLI with -var, variable files with -var-file, or environment variables.
Use .tfvars files for managing multiple variables cleanly.
Avoid passing sensitive data directly on the command line for security.
Always run terraform init after adding or changing variables.