Listen to this Post
Terraform is a powerful infrastructure-as-code tool that allows you to define and provision cloud resources efficiently. One advanced technique is creating a list of lists using Terraform’s `for` loop. This approach helps in managing complex configurations dynamically.
You Should Know:
1. Basic List Creation in Terraform
Before diving into nested lists, let’s see how to create a simple list:
variable "simple_list" { type = list(string) default = ["item1", "item2", "item3"] }
- Creating a List of Lists Using `for` Loop
Harold Finch’s example demonstrates how to generate a nested list structure:output "list_of_lists" { value = [for i in range(3) : [for j in range(2) : "item-${i}-${j}"]] }
Expected Output:
[ ["item-0-0", "item-0-1"], ["item-1-0", "item-1-1"], ["item-2-0", "item-2-1"] ]
3. Advanced Use Case: Dynamic Nested Lists
If you need to generate lists based on existing variables:
variable "regions" { type = list(string) default = ["us-east-1", "us-west-2"] } variable "services" { type = list(string) default = ["ec2", "s3"] } output "dynamic_nested_list" { value = [for region in var.regions : [for service in var.services : "${region}-${service}"]] }
Expected Output:
[ ["us-east-1-ec2", "us-east-1-s3"], ["us-west-2-ec2", "us-west-2-s3"] ]
4. Flattening Nested Lists
To convert a list of lists into a single list, use flatten
:
output "flattened_list" { value = flatten([for i in range(3) : [for j in range(2) : "item-${i}-${j}"]]) }
Expected Output:
["item-0-0", "item-0-1", "item-1-0", "item-1-1", "item-2-0", "item-2-1"]
5. Real-World Example: Multi-Region AWS Deployment
locals { regions = ["us-east-1", "eu-west-1"] ami_ids = { "us-east-1" = "ami-12345678" "eu-west-1" = "ami-87654321" } } resource "aws_instance" "example" { for_each = { for idx, region in local.regions : region => idx } ami = local.ami_ids[each.key] instance_type = "t2.micro" }
What Undercode Say:
Terraform’s `for` loops and list manipulations are essential for scalable infrastructure automation. Here are some related Linux/Windows commands for automation:
Linux Commands:
– `jq` (JSON processor for Terraform outputs):
terraform output -json | jq '.list_of_lists.value'
– `awk` for parsing Terraform state:
terraform show -json | awk '/"type":/ {print $2}'
Windows Commands:
- PowerShell for Terraform automation:
terraform plan -out tfplan | ConvertFrom-Json
AWS CLI Integration:
aws ec2 describe-instances --filters "Name=instance-type,Values=t2.micro" --query 'Reservations[].Instances[].InstanceId'
Expected Output:
Mastering Terraform’s `for` loops and nested lists enables dynamic infrastructure management. Combine these with scripting tools (jq
, awk
, AWS CLI) for full automation.
Reference:
How to build list of lists with terraform for loop
References:
Reported By: Darryl Ruggles – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅