CodexBloom - Programming Q&A Platform

Terraform Applying Multiple Subnets Using Count but Getting 'Invalid Index' scenarios

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-26
terraform aws subnet HCL

I'm having a hard time understanding I've been researching this but I tried several approaches but none seem to work. I'm trying to provision multiple subnets in AWS using Terraform with the `count` argument, but I'm working with an 'Invalid index' behavior during the apply stage. Here's the relevant portion of my code: ```hcl resource "aws_vpc" "main" { cidr_block = "10.0.0.0/16" } variable "subnet_cidrs" { default = ["10.0.1.0/24", "10.0.2.0/24"] } resource "aws_subnet" "subnets" { count = length(var.subnet_cidrs) vpc_id = aws_vpc.main.id cidr_block = var.subnet_cidrs[count.index] } ``` When I run `terraform apply`, I get the behavior message: `behavior: Invalid index 2 (out of range for list of length 2)`. This seems to suggest that it's trying to access an index that doesn't exist in the subnet_cidrs list. I've double-checked the count attribute, and it correctly reflects the length of the list. I even tried hardcoding the index and it worked fine, so I believe there might be an scenario with how I'm referencing `count.index`. I've also ensured that I don't have any other resources in the same configuration that might be modifying the list's length unexpectedly. Has anyone experienced this before? I'm using Terraform v1.3.6. Any help would be appreciated! I'm working on a CLI tool that needs to handle this. How would you solve this? This is for a desktop app running on Linux. Has anyone dealt with something similar? I'm working in a Ubuntu 20.04 environment. Any advice would be much appreciated.