Error: Invalid Index, is empty tuple, The given key does not identify an element in this collection value

Hi I am working on terrafrom verion 0.14.5 and facing error of Invalid Index followed by empty tuple. This is my code.

resource “azurerm_lb” “lb_app_primary” {
count = var.instances_count >= 1 ? 1 : 0
name = “LB1”
sku = “standard”
location = var.location
resource_group_name = var.resourcegroup
}

resource “azurerm_lb_probe” “lb_sql_probe_primary” {
resource_group_name = var.resourcegroup
loadbalancer_id = azurerm_lb.lb_sql_primary[0].id
name = “SQLEndPointProbe”
port = 1433
interval_in_seconds = 10
number_of_probes = 3
}

Variable var.instances_count is of type number.

When initial value of var.instances_count is set to 0 in relevant tfvars file and I execute terraform plan -var-file=setenv.tfvars it fails with below error.

Error: Invalid index

** on modules\CMS\loadbalancers.tf line 176, in resource “azurerm_lb_probe” “lb_sql_probe_primary”:**
** 176: loadbalancer_id = azurerm_lb.lb_sql_primary[0].id**
** |----------------**
** | azurerm_lb.lb_sql_primary is empty tuple**

The given key does not identify an element in this collection value.

When initial value of var.instances_count is set to 1 in relevant tfvars file and I execute terraform plan -var-file=setenv.tfvars, everything works fine and the plan is executed.

I have a requirement to make var.instances to 0 in the tfvars file and terraform plan should execute because we don’t need certain resources to be created for every environment.

I have explored earlier posts with this forum and also tried to apply the solutions provided there but nothing has worked so far. Can you please suggest how do I eliminate this error and have my plan executed with valur ‘0’ in tfvars file.

You’d have to also create this resource conditionally. So, e.g. you have to add the same count parameter.