Introduction
Problem
A user may encounter the following error while running a terraform plan or apply:
Error: Invalid index
│
│ on main.tf line 16, in resource "aws_s3_bucket" "first-bucket":
│ 16: bucket = "${module.test.names[0]}-bucket"
│ ├────────────────
│ │ module.test.names is empty tuple
│
│ The given key does not identify an element in this collection value: the collection has no elements.
Cause
This error is caused when terraform tries to read an index of a tuple, however that tuple is empty. Please see the example below for a better illustration of the problem:
# main.tf
variable "howmany" {
default = 0
}
module "test" {
source = "./modules/test"
howmany = var.howmany
}
resource "aws_s3_bucket" "first-bucket" {
bucket= "${module.test.names[0]}-bucket"
}
# modules/test/main.tf
variable "howmany" {
}
resource "random_pet" "names" {
count = var.howmany
length = 5
}
output "names" {
value = random_pet.names[*].id
}
Overview of possible solutions
Solutions:
-
Use a try statement that defaults to null or a default value on failure
bucket = try(module.test.names[0], null)
OR
bucket = try(module.test.names[0], "my-first-unique-bucket")
2. Avoid reading the index if the tuple is empty by using a condition
bucket = length(module.test.names) > 0 ? module.test.names[0] : null
OR
bucket = length(module.test.names) > 0 ? module.test.names[0] : "my-first-unique-bucket"
NOTE: You should use null if the argument is optional and a default-value if it is required.
Outcome:
Once the configuration has been updated to use one of the solutions above, re-run the failed plan/apply and validate it succeeds. If it fails, verify you are using the correct solution