⚡ ~/naveed Interview Prep
⚡ Portfolio Home 👤 About Naveed Bio & Credentials 📫 Contact Naveed Get In Touch ✍️ Engineering Blog Deep Dives 🎯 Interview Hub 1,000+ Scenarios ☸️ Kubernetes Mastery Hub 24 Modules 🎮 DevOps Arcade & Quizzes Subnet Blitz ⚡ 🗺️ DevOps Roadmaps PDFs & Guides 🤖 Morpheus Analysis AI Quant ↗ 🛠️ Developer Tools Utilities 🧪 Labs & Experiments 📄 Interactive CV & Certs 🔗 All Links & Socials ⚡ Join The Dispatch (Weekly SRE Newsletter) →
← Back to All Terraform & IaC Interview Questions Scenario 52 of 120 in Terraform & IaC
Senior DevOps / SRE [L2] Terraform Terraform Modules & State Production Scenario [L2]
🎯 Target Role / Context: Terraform Scenario #47 (L2) · Use VPC ID from another module

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.

#Terraform #L2 #IaC #Cloud Infrastructure
🎙️ Candidate Opening & Architectural Context
"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>."
Advertisement
⚡ Recommended Practice Lab

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>.

1️⃣

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_each unless you convert with toset().
  • list(object): use for richer entries, such as name and size per item, with named attributes.
  • Defaults and validation: add a default for optional lists and a validation block 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.
2️⃣

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"] in terraform.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.json file with {"subnets": ["a", "b"]} suits generated input from other tools.
  • Auto-loaded files: terraform.tfvars and files ending in .auto.tfvars load automatically; other names, like prod.tfvars, need -var-file.
Advertisement
3️⃣

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.tfvars then evaluate var.subnets and length(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 to each.value.
  • Validation errors: a failed validation block stops plan with your message, a cheap early check. Add a clear error_message that 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 use try() or element() deliberately.
4️⃣

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 -var and -var-file in 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_each with 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.
5️⃣

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.tfvars and prod.tfvars in 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 description and example so callers know whether to supply a list, set or map.
💡 The Senior SRE Gold Nugget (Key Architectural Takeaway)
"Pro-Tip: Prefer tfvars files with a typed variable and validation, and use <code>toset()</code> or a map with stable keys when iterating so reordering the list does not recreate resources."
⚡ 60-Second Elevator Pitch Talking Points
  • 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.
⛔ Critical Candidate Mistakes to Avoid in This Scenario

Senior hiring managers and bar raisers evaluate how you prioritize during outages. Avoid these common anti-patterns:

  1. Mangling shell quotes on the -var flag The inner double quotes get stripped and Terraform reports an invalid value.
  2. Using a list with for_each directly for_each needs a set or map; wrap with toset() or the plan errors.
  3. Relying on list order for indexed resources Reordering or removing an item shifts indexes and recreates resources.
  4. Committing secrets inside tfvars The values land in git history and in logs.
Advertisement
Want more Terraform & IaC scenarios?
Explore our complete collection of scenario-based Terraform & IaC interview runbooks.
Browse All Terraform & IaC Questions →