Search code examples
terraformazure-rm

Create azurerm_sql_firewall_rule for an azurerm_app_service_plan in Terraform


I want to whitelist the ip addresses of an App Service Plan on a managed Sql Server.
The problem is, the resource azurerm_app_service_plan exposes its ip addresses as a comma-separated value, on the attribute possible_outbound_ip_addresses.

I need to create one azurerm_sql_firewall_rule for each of these ips.
If I try the following approach, Terraform gives an exception:

locals {
   staging_app_service_ip = {
      for v in split(",", azurerm_function_app.prs.possible_outbound_ip_addresses) : v => v
   }
}

resource "azurerm_sql_firewall_rule" "example" {
  for_each            = local.staging_app_service_ip
  name                = "my_rules_${each.value}"
  resource_group_name = data.azurerm_resource_group.example.name
  server_name         = var.MY_SERVER_NAME
  start_ip_address    = each.value
  end_ip_address      = each.value
}

I get then the error:

The "for_each" value depends on resource attributes that cannot be determined until apply, so Terraform cannot predict how many instances will be created. To work around this, use the -target argument to first apply only the resources that the for_each depends on.

I'm not sure how to work around this.
For the time being, I have added the ip addresses as a variable, and am manually setting the value of the variable.

What would be the correct approach to create these firewall rules?


Solution

  • I'm trying to deal with the same issue. My way around it is to perform multi-step setup. In the first step I run terraform configuration where it creates database, app service, api management and some other resources. Next I deploy the app. Lastly I run terraform again, but this time the second configuration creates sql firewall rules and api management api from deployed app swagger definition.