List Variable

A list variable holds a list of values (for example, name of users) to be used. Each list variable specifies the order.

let see with example create a file variable.tf with below contents.

variable users {
    type = list
}

let's create one more file that will access user from the users variables. (list variable.)

output printfirst {
  value = "first user is ${(var.users[1])}"
}

in the above file we will accessing second element of the array. because indexing starting from the zero. let run the terraform plan and see the output.

┌──(gaurav㉿learning-ocean)-[~/youtube-course/list-variable]
└─$ terraform plan
var.users
  Enter a value: [ "gaurav", "saurav", "ankit"]
Changes to Outputs:
  + printfirst = "first user is saurav"
You can apply this plan to save these new output values to the Terraform state, without changing any real infrastructure.

here we can see the second element of the array in the output.

we can add the default value using the below snippet

variable users {
  type = list
  default = ["gaurav","Saurav","anKit"]
}

and we can pass the list variable from the command line using below syntax.

terraform plan -var 'variablename=["valueone","valuetwo","value3"]'

let's run terraform apply and see it in action.

┌──(gaurav㉿learning-ocean)-[~/youtube-course/list-variable]
└─$ terraform plan -var 'users=["gaurav","saurav","ankit"]'

Changes to Outputs:
  + printfirst = "first user is saurav"

You can apply this plan to save these new output values to the Terraform state, without changing any real infrastructure.
─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Note: You didn't use the -out option to save this plan, so Terraform can't guarantee to take exactly these actions if you run "terraform apply" now.
┌──(gaurav㉿learning-ocean)-[~/youtube-course/list-variable]
└─$

Demo Video