I tried 4 different Ways to assign variable in terraform

I tried 4 different Ways to assign variable in terraform

Clock Icon2022.04.26

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

There are various ways to assign variable in Terraform, so I will introduce them.

Introduction to Terraform variables

Just like in other technologies, variables let you customize your Terraform modules and resources without altering the 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 and stage in infrastructure as a code.

This time, as an example, I would like to use the following template

main.tf

provider "aws" {
   region     = "ap-southdeast-1"
   access_key = "your access key"
   secret_key = "Your Secret Access Key"
}

resource "aws_instance" "ec2_example" {

   ami           = "ami-xxxxxxxxxxxxxxxxx"
   instance_type =  var.instance_type

   tags = {
           Name = "Terraform EC2"
   }
}

variable "instance_type" {
   description = "Instance type t2.micro"
   type        = string
   default     = "t2.micro"
}

 

1. Interactive Input – terraform variables

If you execute terraform plan or apply without doing anything, Terraform will ask you to input the variables interactively in user interface.

2. Command-line variables

The most simple way to assign value to a variable is using the -var option in the command line when running the terraform plan and terraform apply commands.

$ terraform apply -var="instance_type=t2.micro"

3. Variable file .tfvars

we can assign variable value in separate file as shown bellow with extension of .tfvars , *.auto.tfvars or *.tfvars.json

we can use this file using -var-file flag

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

4. Environment variables

When running Terraform commands, you can also use Environment Variables to define the values for Input Variables on your Terraform project. Terraform automatically will pull in any Environment Variables that are named using the prefix of TF_VAR_ followed by the name of the Input Variable.

 $ export TF_VAR_instance_type=t2.micro 

Terraform loads variables in the following order:

with 5 taking highest precedence and 1 taking least :

  1. Environment variables
  2. The terraform.tfvars file,
  3. The terraform.tfvars.json file
  4. Any *.auto.tfvars or *.auto.tfvars.json files, processed in lexical order of their filenames.
  5. Any -var and -var-file options on the command line, in the order they are provided. (This includes variables set by a Terraform Cloud workspace.)

Reference:

https://www.terraform.io/language/values/variables

Share this article

facebook logohatena logotwitter logo

© Classmethod, Inc. All rights reserved.