Shashi Techlogues.

Terraform different approaches for variable assignment.

In this post, we will discuss different approaches to variable assignment in Terraform.

Here are the different approaches:

  1. Variable Defaults
  2. Command-line flags
  3. From a file
  4. Environment variables

We will go into detail one by one and see examples of using them.

1. Variable Defaults

In this approach, we create a variables.tf file and define a variable and assign a default value to a variable.

variable "instance_type" {
    default = "t2.micro"
}

This is referred to as a variable default. If no value is mentioned for the variable, then the default value will be assigned.

Here comes the question: what will happen if we don’t provide a default value?

Let’s try it out. We removed the default value and now our variable looks like this.

variable "instance_type" {}

And do a terraform plan:

terraform plan

You will get an output like this:

var.instance_type
  Enter a value:

So, if you have not defined a default value, Terraform will ask you for the value from the command line.

2. Command-Line Flags

In the similar example above, if we have a variable and we have not provided a default value, or we want to override the value, we can do so by providing the value in the command line.

terraform plan --var="instance_type=t2.small"

3. From a File

Another way you can provide a value is using a file. Create a terraform.tfvars file and provide a value for the variables.

# terraform.tfvars
instance_type = "t2.micro"

Now when you do terraform plan, the instance type value will be taken from the terraform.tfvars file.

Note: File naming is important here. Terraform by default only looks for the terraform.tfvars file.

Let’s say for some reason you want to use a custom file name. Create a new file custom.tfvars and delete the terraform.tfvars file.

Now, in order to use custom.tfvars, you can provide the file name in the CLI like below.

terraform plan -var-file="custom.tfvars"

4. Environment Variables

Finally, let’s explore the environment-based approach.

Let’s set an environment variable.

Windows

setx TF_VAR_instance_type t2.micro

The TF_VAR_<VARIABLE> <VALUE> format is Terraform-specific.

Linux / macOS

export TF_VAR_instance_type=t2.micro

Further Reading

Read more about Terraform variables here:

Using Terraform Variables in Detail

In the subsequent article, we will explore more of Terraform.

Thanks for reading. If you have some feedback, please provide your response or reach out to me on Twitter or Github.

Happy Coding!!!