Red 5
Red 5

Reputation: 338

Conditional outputs on data sources in terraform

I have a sql server terraform module that outputs the name of a sql server for the databases to get created in. However, some environments should use an external server outside of the terraform project instead. Most datacenters we have do not have this external server, just a few.

I've set up the external server using data sources as usual, and made both the output, normal server and datasource conditional on a variable thats passed in like this:

variable "use_external_sql_server" {
  type = bool
}

resource "azurerm_mssql_server" "sqlserver" {
  count = var.use_external_sql_server ? 0 : 1
  name = "sql-interal-sql_server"
  ....
}

data "azurerm_mssql_server" "external_sql_server" {
  count = var.use_external_sql_server ? 1 : 0
  name                = "sql-${var.env}-${var.location}"
  resource_group_name = "rg-${var.env}-${var.location}"
}

output "sql_server_name" {
    value = var.use_external_sql_server ? data.azurerm_mssql_server.external_sql_server.name : azurerm_mssql_server.sqlserver[0].name
    depends_on = [
      azurerm_mssql_server.sqlserver,
      data.azurerm_mssql_server.external_sql_server
    ]
}

However, I'm running into issues with the output. It requires data.azurerm_mssql_server.external_sql_server to exist to evaulate the condition, even if "use_external_server" is false. This is not ideal as I have to manual create dummy servers to fix this condition, so that that conditional can evaulate to true.

Is there a way to do this conditional without having to have "data.azurerm_mssql_server.external_sql_server" actually exist?

Upvotes: 1

Views: 1723

Answers (1)

Chris Doyle
Chris Doyle

Reputation: 11992

You could get rid of the conditional in the output and just use a try.

try evaluates all of its argument expressions in turn and returns the result of the first one that does not produce any errors. This is a special function that is able to catch errors produced when evaluating its arguments, which is particularly useful when working with complex data structures whose shape is not well-known at implementation time.

You could then possibly write something like

output "sql_server_name" {
    value = try(data.azurerm_mssql_server.external_sql_server[0].name, azurerm_mssql_server.sqlserver[0].name, "")
    depends_on = [
      azurerm_mssql_server.sqlserver,
      data.azurerm_mssql_server.external_sql_server
    ]
}

Upvotes: 2

Related Questions