- Hardcoded values prevent easy reuse across environments.
- Editing multiple resource blocks for a simple change is error-prone.
- Sharing or versioning configurations becomes harder.
variables.tf file and reference them using var.<name> from your resource files (main.tf, etc.).
Variables declaration (variables.tf):
main.tf):
var.location and var.resource_group_name allows multiple resources to reuse the same inputs. If the region or resource group needs to change, update the variable defaults or supply different values at runtime in one place instead of editing every resource block.
Variables can be provided by default values, environment variables, a
.tfvars file, or via CLI flags when you run Terraform. This makes configurations portable and easier to manage across environments.
Demonstration: creating variables and resources in a project directory
- We’ll create a small Terraform project that defines a provider, variables, and a single resource group resource.
- For brevity, this demo uses simpler variable names (
rgandregion) to illustrate the same concept.
provider.tf):
variables.tf):
main.tf):
terraform init output:
terraform plan output:
eastus and kodekloud-tf-var-rg) rather than var.rg or var.region. This makes it easy to review what Terraform will deploy.
Do not store sensitive secrets (API keys, passwords) in plaintext
variables.tf defaults or checked-in .tfvars files. Use environment variables, Terraform Cloud/Enterprise workspace variables, or secret management integrations to protect sensitive data.
Summary
- Declaring variables decouples configuration values from resource blocks, improving reusability and maintainability.
- Use
var.<name>in resource blocks to reference declared variables. - Variable values can be supplied via defaults, environment variables (
TF_VAR_),.tfvarsfiles, or CLI-varflags. - For secrets, avoid checked-in defaults and prefer secure secret mechanisms.
variable block would cover advanced topics such as type constraints, validation blocks, sensitive attributes, and multiple ways to provide variable values across CI/CD and team workflows.