Interview Prep/Terraform/Plan Errors and Unexpected Replacements

`Error: Invalid index` — `The given key does not identify an element in this collection value: the collection has no elements.`

IntermediateTroubleshootingPlan Errors and Unexpected Replacements
Answer

Likely causes → Accessing [0] on an empty list: a data source with no matches (data.aws_subnets.private.ids[0]), or a resource with count = 0.

Diagnose → terraform console → data.aws_subnets.private.ids and check filters/tags.

Fix → Fix the filter, or guard: one(aws_eip.nat[*].public_ip) (null when empty) or try(x[0], null). For required inputs, add a postcondition with a clear message.

Prevent → Add lifecycle { postcondition { condition = length(self.ids) > 0 ... } } on critical data sources.

All Terraform questions

More on Plan Errors and Unexpected Replacements