Terraform variables
Variables in terraform are input values used to parameterize your configuration.
They are defined in a variables.tf
file and there are a few ways to load them into terraform.
variable "image_id" {
type = string
default = ""
}
.tfvars files
These are reusable files used to overwrite the values in variables.tf
file.
var_name=“value”
The format is similar to a .env file.
It isi common to have a file per environment dev.tfvars
, prod.tfvars
You pass the name of the file to a terraform call using -var-file
-var
You can pass individual variables into terraform using -var
terraform plan -var “name=red”
This is fine for adhoc stuff but it’s likely you’ll want to use environment variables.
TF_VAR
You can set an environment variable with a prefix of TF_VAR_
followed by the variable name in your variables.tf
file.
export TF_VAR_name=red
This will overwrite the default value in the variables.tf
file.
Makefile
A makefile is helpful when running your terraform commands as you can have one for each environment configured to pass the correct tfvars file
plan:
terraform plan -var-file=“dev.tfvars
or if you have a .env file you can load in the variables using include
, and prefix if needed.
include ../.env.local
export TF_VAR_cloudflare_api_token=$(CLOUDFLARE_API_TOKEN)