Terraform TFVARs Files

To set lots of variables, it is more convenient to specify their values in a variable definitions file (with a filename ending in either .tfvars or .tfvars.json).

Terraform automatically loads a number of variable definitions files if they are present:

  1. Files named exactly terraform.tfvars or terraform.tfvars.json.
  2. Any files with names ending in .auto.tfvars or .auto.tfvars.json.

let's take an example

create a file with tf extension

variable age {
    type = number
}

variable "username" {
  type = string
}

output printname {
        value = "Hello, ${var.username}, your age is ${var.age}"
}

create a file with terraform.tfvars

age=25
username="Gaurav Sharma"

now lets run command terraform plan or terraform apply

┌──(gaurav㉿learning-ocean)-[~/terraform/youtube-course/tf-var]
└─$ terraform plan
Changes to Outputs:
  + printname = "Hello, Gaurav Sharma, your age is 25"

You can apply this plan to save these new output values to the Terraform state, without changing any real infrastructure.
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Note: You didn't use the -out option to save this plan, so Terraform can't guarantee to take exactly these actions if you run "terraform apply" now.

TFVARs File With Different Name

if you have .tfvars file with different name then need to specify the filename explicitly like the below command

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

let's take an how can we use tfvars file with a different name other than terraform.tfvars

create a file with tf extension

variable age {
    type = number
}

variable "username" {
  type = string
}

output printname {
        value = "Hello, ${var.username}, your age is ${var.age}"
}

create a file with development.tfvars (you can change it as per your requirement)

age=25
username="Saurav Sharma"

now run the below command and specify the tfvar files explicity.

┌──(gaurav㉿learning-ocean)-[~/terraform/youtube-course/tf-var-custom]
└─$ terraform plan --var-file development.tfvars
Changes to Outputs:
  + printname = "Hello, Saurav Sharma, your age is 25"

You can apply this plan to save these new output values to the Terraform state, without changing any real infrastructure.
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Note: You didn't use the -out option to save this plan, so Terraform can't guarantee to take exactly these actions if you run "terraform apply" now.

Demo Video