We come in this part 2 and we are going to discuss about Terraform variables. Terraform supports variable assignment in their way. Let's see how.


Declare a variable

We usually declare a Terraform variable  in this format.

variable "<name>" {
  type    = <type>
  default = <default_value>

type and default are frequently used attributes. For other attributes. Please visit the link below for more info.

Input Variables - Configuration Language | Terraform | HashiCorp Developer
Input variables allow you to customize modules without altering their source code. Learn how to declare, define, and reference variables in configurations.

Assign a value to a variable

Then we can assign a value to a variable using this simple syntax.

<name> = <value>

Assign a variable to a resource

Then we can assign a variable to an attribute of a resource using var. followed by the variable name, like this.

resource "resource_A" "resource_name_A" {
  attribute_1 = var.<variable_name_1>
  attribute_2 = var.<variable_name_2>

VSCode Plugin

This will be more useful when we develop a Terraform script with a good IDE and a good plugin. For me, I would love to share this plugin for VSCode and we can write a lot faster with its auto-complete on variable assignment.

HashiCorp Terraform - Visual Studio Marketplace
Extension for Visual Studio Code - Syntax highlighting and autocompletion for Terraform

And the auto-complete will be ready like this.

Files pattern

We can write all in a single file but I suggest to split the files into this. It would be useful when we have multiple sets of variable, multiple environments.

├── main.tf
├── variables.tf
└── var-dev.vars

main.tf is our first tf script.

variables.tf is the variable declaration file.

var-dev.vars is the variable assignment file. As aforementioned, name can be anything also the extention. We can name it dev.tfvars or something else, just make sure the contents inside is according to the variable assignment syntax above. However, I recommend to have .tfvars so the plugin can work perfectly, but not this time ;P

And here are the sample files.





Now our files are ready there. Let's go to the execution part.


Say validation completes and to plan, if we run this.

terraform plan

Terraform could detect there are variables in the script and ask us the values. Like this.

Because we have variable file now we can input the file using this command.

terraform plan -var-file=<filepath>


Everything is fine so we can apply with the variable file and force approval.

terraform apply -var-file=<filepath> -auto-approve


Cleanup the resouce with the command.

terraform destroy -var-file=<filepath> -auto-approve

Now we can customize the variables into our use cases.