'Unable to attach the certificate from a keyvault in a different subscription to an app service

The app service is in subscription1 and the keyvault is in subscription2, I want to attach the certificate in the keyvault to the appservice during the terraform deployment and I keep getting the error Error: Unable to determine the Resource ID for the Key Vault at URL "https://.vault.azure.net/"

If I skip the certificate and secret data source, and use the keyvault_secret_id, I get the error that Code="Forbidden" Message="Client address is not authorized and caller is not a trusted service.

This is the below code:

data "azurerm_key_vault" "kvprod" {
  provider            = azurerm.<alias>
  name                = "<keyvaultname>"
  resource_group_name = "<keyvaultrgname>"
}

data "azurerm_key_vault_certificate" "kvcertificate" {
  provider     = azurerm.<alias>
  name         = "<certifinatename>"
  key_vault_id = data.azurerm_key_vault.kvprod.id
}

data "azurerm_key_vault_secret" "kvsecret" {
  provider     = azurerm.<alias>
  name         = data.azurerm_key_vault_certificate.kvcertificate.name
  key_vault_id = data.azurerm_key_vault.kvprod.id
}

 resource "azurerm_app_service_certificate" "certificate" { 
  name                = "<certifinatename>"
  location            = data.azurerm_resource_group.<appservicerg>.location 
  resource_group_name = data.azurerm_resource_group.<appservicerg>.name
  pfx_blob            = data.azurerm_key_vault_secret.kv.value
  #key_vault_secret_id = "<keyvaultID>"
}


Solution 1:[1]

One thing you have to do is to ad app service principal to key vault policy

data "azuread_service_principal" "web_app_resource_provider" {
  application_id = "abfa0a7c-a6b6-4736-8310-5855508787cd"
}

resource "azurerm_key_vault_access_policy" "web_app_resource_provider" {
  key_vault_id            = module.key_vault.key_vault_id
  tenant_id               = data.azurerm_client_config.current.tenant_id
  object_id               = data.azuread_service_principal.web_app_resource_provider.id
  secret_permissions      = ["Get"]
  certificate_permissions = ["Get"]
}

That beeing said you will get another error

Error: Unable to determine the Resource ID for the Key Vault at URL

It seems that terraform is unable to create app service cert in diffrent resource group and subsciprtion.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Arkadiusz Spiewak