How do I obtain a default value when a tuple is empty in my Terraform template?

Viewed 7169

I have a locals block as follows:

locals {
  database_server_name = var.createDatabaseServer ? azurerm_postgresql_server.region[0].name : var.postgresqlServerName
}

Unfortunately, it seems like Terraform wants to evaluate the tuple (region[0]), despite not having to in every scenario:

Error: Invalid index

  on terraform/region/03-database.tf line 34, in locals:
  34:   database_server_name = var.createDatabaseServer ? azurerm_postgresql_server.region[0].name : var.postgresqlServerName
    |----------------
    | azurerm_postgresql_server.region is empty tuple

Is there any way to accomplish what I want above where a default value (var.postgresqlServerName) can be used in situations where the tuple is empty?

2 Answers

From just the information you shared it's not clear how var.createDatabaseServer and azurerm_postgresql_server.region are related, and thus not clear what might cause evaluation of the first expression of the conditional in situations where it's not appropriate.

With that said, you may be able to get the answer you were looking for by directly testing for whether the situation you are expecting is true, rather than inferring it by testing another variable:

locals {
  database_server_name = (
    length(azurerm_postgresql_server.region) > 0 ?
    azurerm_postgresql_server.region[0].name :
    var.postgresql_server_name
  )
}

By directly testing how many elements there are in azurerm_postgresql_server.region you can avoid any situation where the condition and the first expression would disagree with each other.

Maybe take the logic out of the local and create the resource conditionally. Where you consume local.database_server_name could contain a count or for_each (which can contain other logic):

resource "azurerm_postgresql_server" "foo" {
  count = var.createDatabaseServer ? 1 : 0
  name = var.postgresqlServerName
  ...
}
Related