Post

Let's try: Terraform part 2 - variables

Terraform supports variable assignment in their way. Let's see how.

Let's try: Terraform part 2 - variables
In this series

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.


Declarations

Declare a variable

We usually declare a Terraform variable in this format.

1
2
3
4
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.

Assign a value to a variable

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

1
<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.

1
2
3
4
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.

And the auto-complete will be ready like this.

plugin


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.

1
2
3
4
.
├── 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.

main.tf

variables.tf

var-dev.vars


Executions

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

Plan

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

1
terraform plan

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

plan

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

1
terraform plan -var-file=<filepath>

plan with vars

Apply

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

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

apply

Destroy

Cleanup the resouce with the command.

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

destroy


Now we can customize the variables into our use cases.

This post is licensed under CC BY 4.0 by the author.