Search code examples
terraformterraform-provider-azure

Problem with Terraform erroring on resource creation because of a missing referenced attribute that will be created


I desire to add a Key Vault access policy for an App Service which will use the App Services managed identity. If I add the required identity attribute as type "System Assigned" to the App Service and the Key Vault access policy referencing the "to be" created object id for the managed identity of the existing App Service, I get an error during plan/apply stating that "The argument "object_id" is required, but no definition was found.". Code example:

resource "azurerm_linux_web_app" "webapp1" {
  name                = "app-web-myapp-test3"
  resource_group_name = azurerm_resource_group.secondary_rg.name
  location            = azurerm_resource_group.secondary_rg.location
  service_plan_id     = data.terraform_remote_state.shared_resources.outputs.primary_plan_id
  identity {
    type = "SystemAssigned"
  }

  site_config {
    always_on = false
  }
}


resource "azurerm_key_vault_access_policy" "secondary_policy" {
  key_vault_id = data.terraform_remote_state.shared_resources.outputs.primary_vault_id
  tenant_id    = data.azurerm_client_config.current.tenant_id
  object_id          = azurerm_linux_web_app.webapp1.identity.0.principal_id
  secret_permissions = ["Get", ]
     depends_on = [
      azurerm_linux_web_app.webapp1
     ]
}

Using a depends on for the App Service doesn't help because the resource already exists (but not the required attribute) and thus fails. Depends on does not permit itself to be used on an attribute, only the resource. If I first apply the managed identity change to the app service and then after completion, add the Key Vault policy, it works fine. If I run it from scratch before the App Service is create, it waits for the App Service to be created with the managed identity, and works fine. However, I want to keep the App Service in place and apply these changes during the same apply. How can this dependency be handled?


Solution

  • This workaround also works for web apps: https://github.com/hashicorp/terraform-provider-azurerm/issues/19316

    Essentially, referencing a data source rather than the resource directly.