Terraform - Define variables in terraform.tfvars files

by
Jeremy Canfield |
Updated: August 01 2023
| Terraform articles
Let's say you have the following files on your Terraform server.
├── main.tf (root module)
├── data.tf
├── locals.tf
├── outputs.tf
├── providers.tf
├── terraform.tfstate
├── variables.tf
├── child (directory)
│ ├── main.tf (child module)
│ ├── data.tf
│ ├── outputs.tf
│ ├── resources.tf
Variables can be defined in a file. If the file is named terraform.tfvars, the variables will be available to all modules at or below the directory that contains the terraform.tfvars file. Let's say terraform.tfvars contains the following.
username = "john.doe"
password = "itsasecret"
You should then be able to use the variables in your modules. For example, let's say outputs.tf in the same directory as your main root module (main.tf) has the following.
output "username" {
value = var.username
}
output "password" {
value = var.password
}
The terraform refresh or terraform plan or terraform apply or terraform output commands should then return something like this.
username = "john.doe"
password = "itsasecret"
Did you find this article helpful?
If so, consider buying me a coffee over at