Q: How do you pass a list of values to a Terraform variable?
To pass a list of values to a Terraform variable, declare it with type = list(string) and supply it in a .tfvars file as subnets = ["a", "b"], or on the command line with -var or the TF_VAR_subnets environment variable using the.
Want to master this scenario in a live sandbox? KodeKloud's HashiCorp Certified Terraform Associate (003) Interactive Labs covers this exact problem with hands-on terminal drills.
🛠️ Production Runbook & Step-by-Step Resolution
Direct Answer: To pass a list of values to a Terraform variable, declare it with <code>type = list(string)</code> and supply it in a <code>.tfvars</code> file as <code>subnets = ["a", "b"]</code>, or on the command line with <code>-var</code> or the <code>TF_VAR_subnets</code> environment variable using the same HCL syntax. Interviewers ask this to test your grasp of variable types, the precedence order of inputs, shell quoting pitfalls, and the difference between lists and sets when later using <code>for_each</code>.
Declare the list type first
The type decides parsing, validation and how you can iterate. Choosing the right type up front gives clearer errors and prevents surprises when you later iterate over the values.
variable "subnets" {
type = list(string)
description = "Subnet IDs for the load balancer"
validation {
condition = length(var.subnets) >= 2
error_message = "Provide at least two subnets."
}
}
- list(string): ordered, allows duplicates, accessed by index such as
var.subnets[0]. It is the most common choice for subnet IDs, CIDR blocks and availability zones. - set(string): unordered and unique; required by
for_eachunless you convert withtoset(). - list(object): use for richer entries, such as name and size per item, with named attributes.
- Defaults and validation: add a
defaultfor optional lists and avalidationblock for rules like non-empty. - Nested types: for items with several fields,
list(object({ name = string, size = number }))documents the shape and gives clear type errors when input is wrong.
Hands-on: pass a list of values to a Terraform variable
Four supported input methods, all using HCL list syntax. All four routes feed the same variable, so the real question is which one fits your workflow and how they override each other.
# prod.tfvars
subnets = ["subnet-0aaa", "subnet-0bbb"]
terraform plan -var-file=prod.tfvars
terraform plan -var='subnets=["subnet-0aaa","subnet-0bbb"]'
export TF_VAR_subnets='["subnet-0aaa","subnet-0bbb"]'
terraform plan
- tfvars file: put
subnets = ["subnet-a", "subnet-b"]interraform.tfvars, any*.auto.tfvars, or a file passed with-var-file. - CLI flag:
-var='subnets=["subnet-a","subnet-b"]'; use single quotes outside so the shell keeps the inner double quotes. On Windows shells, quoting rules differ, so a file is safer. - Environment:
TF_VAR_subnets='["subnet-a","subnet-b"]'is parsed the same way for complex types. - JSON: a
terraform.tfvars.jsonfile with{"subnets": ["a", "b"]}suits generated input from other tools. - Auto-loaded files:
terraform.tfvarsand files ending in.auto.tfvarsload automatically; other names, likeprod.tfvars, need-var-file.
Verify the value Terraform received
Do not guess how the input was parsed. Printing the parsed value takes seconds and removes any doubt about quoting or type conversion.
$ terraform console -var-file=prod.tfvars
> var.subnets
[
"subnet-0aaa",
"subnet-0bbb",
]
> length(var.subnets)
2
- Console:
terraform console -var-file=prod.tfvarsthen evaluatevar.subnetsandlength(var.subnets). - Plan: review resources that consume the list; a wrong length shows as unexpected adds or removes.
- Iteration: convert for use with for_each:
for_each = toset(var.subnets)and refer toeach.value. - Validation errors: a failed
validationblock stops plan with your message, a cheap early check. Add a clearerror_messagethat tells the caller exactly what to fix. - Indexing: reading
var.subnets[2]beyond the list length errors at plan, so pair indexing with a length validation or usetry()orelement()deliberately.
Precedence and failure modes
Several sources can set the same variable; later ones win. Knowing the precedence prevents the confusing situation where a value in a file is silently overridden elsewhere. Keep the number of sources small to stay predictable.
- Order (low to high): defaults, environment variables
TF_VAR_*,terraform.tfvars,terraform.tfvars.json,*.auto.tfvars, then-varand-var-filein the order given. - Quoting errors: unquoted brackets or missing inner quotes produce "Invalid value for input variable"; test the exact shell line.
- Type mismatch: passing a plain string to a list variable fails; wrap in brackets.
- Order changes: a list reorder changes indexed resources and may force recreation; prefer maps or
for_eachwith stable keys. - Windows shells: PowerShell and cmd treat quotes differently from bash; prefer a tfvars file or a JSON file to avoid quoting problems in cross-platform teams.
Production practice
Keep inputs reviewable and environment specific. Consistent, typed inputs make the same code safe to run across many environments.
- Per environment files: keep
dev.tfvarsandprod.tfvarsin version control for non-secret values. - Secrets: do not place secrets in tfvars committed to git; inject them from the CI secret store as
TF_VAR_*variables. - Typed objects: prefer
list(object({...}))or a map with validation over loosely typed lists of strings. - Pipelines: store non-secret tfvars in the repository and pass the file name per environment with
-var-file, so the same pipeline can promote dev to prod. - Documentation: give every variable a
descriptionand example so callers know whether to supply a list, set or map.
- You declare type = list(string) and pass it as an HCL list via tfvars, -var, TF_VAR_ or a JSON file.
- I verify with terraform console and the plan, and I know that -var and -var-file override tfvars and env vars.
- I keep per environment tfvars in git, inject secrets from CI and use validation blocks.
Senior hiring managers and bar raisers evaluate how you prioritize during outages. Avoid these common anti-patterns:
- Mangling shell quotes on the -var flag The inner double quotes get stripped and Terraform reports an invalid value.
- Using a list with for_each directly for_each needs a set or map; wrap with toset() or the plan errors.
- Relying on list order for indexed resources Reordering or removing an item shifts indexes and recreates resources.
- Committing secrets inside tfvars The values land in git history and in logs.