How to use Terraform variables in different ways

terraform
Reading Time: 2 minutes

Introduction to Terraform variables

Just like in other technologies, variables let you customize your Terraform modules and resources without altering the modules’ code. Results you do not need to hard code just for a few tweaks in your resources.

Using variables is very handy when you are creating the same resources but with different configurations.

For example:

  • S3 bucket for diffrent regions
  • EC2 instances of diffrent sizes
  • Different type of ami of EC2 instances
  • And so on & much more…

Different ways to use Terraform variables

1. Interactive Input – terraform variables

Just don’t give default value. Terraform will ask for value at the runtime of the creation of resources.
[Note: Best Practice is to keep all variables in separate vars.tf file in the same directory]

vars.tf

variable "con" {
  description = "Enter content of demo.txt file"
  type = string
}

main.tf

resource "local_file" "demo" {
  content = var.con
  filename  = "demo.txt"
}

When you perform terraform apply terraform will ask you for a value of your variable.

console image

2. Command-line variables

You can pass command line variables at the time of apply action

Syntax: $ terraform apply -var “<varname>=<value>”

main.tf

variable "con" {
  description = "Enter content of demo.txt file"
  type = string
}
resource "local_file" "demo" {
  content = var.con
  filename  = "demo.txt"
}

Run the apply command

terrform apply -var "con=hello terraform"
output image

3. Variable file .tfvars

main.tf

variable "con" {
  description = "Enter content of demo.txt file"
  type = string
  default = "default value of this variable"
}
resource "local_file" "demo" {
  content = var.con
  filename  = "demo.txt"
}

terraform.tfvars

con = "im variable"

Run the apply command

terraform apply
output image

Terraform look for terraform.tfvars . If you created multiple files with different names. You can specify the filename

terraform apply -var-file=demo.tfvars

4. Environment variables

Set environment variable with prefix “TF_VAR”

export TF_VAR_con="hello env"

Run the apply command

terraform apply
output image

Variables Definition Precedence

The highest precedence order will overwrite the lower ones.

precedence of variables

References

All about Terraform basics

Written by 

Rahul Soni is a Software Consultant at Knoldus Software. He is always charged up for new things & learnings. He is dedicated to his work and believes in quality output. He loves to take deep dives into cloud technologies & different tools.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading