How to Use List Variable in Terraform: Syntax and Example
In Terraform, you define a list variable using
variable block with type = list(string) or similar. You can then reference this list variable in your configuration using var.variable_name to use multiple values easily.Syntax
To declare a list variable in Terraform, use the variable block with type = list(TYPE). You can set a default list or provide values during runtime.
- variable_name: The name of the variable.
- type: Specifies the variable as a list of a certain type, e.g.,
list(string). - default: Optional default list values.
terraform
variable "example_list" { type = list(string) default = ["value1", "value2", "value3"] }
Example
This example shows how to define a list variable and use it to create multiple AWS S3 buckets with names from the list.
terraform
variable "bucket_names" { type = list(string) default = ["bucket-one", "bucket-two", "bucket-three"] } resource "aws_s3_bucket" "buckets" { for_each = toset(var.bucket_names) bucket = each.value acl = "private" }
Output
Creates three S3 buckets named bucket-one, bucket-two, and bucket-three with private ACL.
Common Pitfalls
Common mistakes when using list variables include:
- Not specifying the
typeas a list, which can cause errors. - Using a string instead of a list, e.g.,
default = "value1,value2"instead ofdefault = ["value1", "value2"]. - Trying to use list variables without converting to a set when using
for_each.
terraform
variable "wrong_list" { default = "value1,value2" } # Correct way: variable "correct_list" { type = list(string) default = ["value1", "value2"] }
Quick Reference
| Concept | Description | Example |
|---|---|---|
| Declare list variable | Use variable block with type list | variable "names" { type = list(string) } |
| Set default list | Provide default values as list | default = ["a", "b", "c"] |
| Reference list | Use var.variable_name to access | var.names |
| Use in for_each | Convert list to set for for_each | for_each = toset(var.names) |
Key Takeaways
Always declare list variables with explicit type = list(TYPE) for clarity and validation.
Use square brackets [ ] to define list values, not comma-separated strings.
Access list variables with var.variable_name in your Terraform code.
Convert lists to sets with toset() when using for_each to avoid errors.
Providing default values in list variables helps avoid errors when no input is given.