Input Variable – without default value

variable "image_id" {
  type = string

Input Variable – with default value

variable "availability_zone_names" {
  type    = list(string)
  default = ["us-west-1a"]

Using -var

T‍he most basic way of providing single variable override for a terraform apply command using the -var option

terraform apply -var region=”us-east-1” -var stage=”production” -var instance_type=”t3.large”

In pipeline, we can use some environment variables, which looks more professional

terraform apply -var region=”$MY_REGION” -var stage=”$MY_STAGE” -var instance_type=”$MY_INSTANCE_TYPE”

Using TF_VAR

Terraform will check environment variable has prefixed with TF_VAR_ and use it as an input variable. So, if we define an environment variable called TF_VAR_region, then Terraform will use its value as variable named region.

Using tfvars files

Create a file named example.tfvars

instance_type = “t3.medium”

And then run 

terraform apply -var-file=example.tfvars

Multiple var file adding

terraform apply -var-file=”us.tfvars” -var-file “large.tfvars”

What is the difference between variable TF and variable Tfvars? is where you declare your variables, while terraform.tfvars is where you assign values to those variables, tfvars will override the, but we will explain precedence later in this article.

Terraform loads variables in the following order, with later sources taking precedence over earlier ones:

  • Environment variables
  • The terraform.tfvars file, if present.
  • The terraform.tfvars.json file, if present.
  • Any *.auto.tfvars or *.auto.tfvars.json files, processed in lexical order of their filenames.
  • 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.)

Bir cevap yazın

E-posta hesabınız yayımlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir