Search code examples
azureazure-web-app-serviceazure-keyvaultazure-managed-identityazure-bicep

Access system assigned Principal Id of managed identity from existing azure resource


I want to create access policy for existing app service that uses System Assigned managed identity:

enter image description here

My code looks like this:

resource apiWeb 'Microsoft.Web/sites@2022-03-01' existing = {
  name: apiWebAppName
}

resource keyVault 'Microsoft.KeyVault/vaults@2022-07-01' = {
  name: keyVaultName
  location: location
  tags: tags
  properties: {
    sku: {
      family: 'A'
      name: 'standard'
    }
    tenantId: tenantId
    accessPolicies: [
      {
        tenantId: tenantId
        objectId: apiWeb.identity.principalId
        permissions: {
          secrets: [
            'get'
            'list'
          ]
        }
      }
    ]
  }
}

And during deplyoment i got error:

{
    "status": "Failed",
    "error": {
        "code": "InvalidTemplate",
        "message": "Unable to process template language expressions for resource '/subscriptions/xyz/resourceGroups/rg/providers/Microsoft.KeyVault/vaults/kv' at line '47' and column '5'. 'The language expression property 'identity' doesn't exist, available properties are 'apiVersion, location, tags, kind, properties, condition, deploymentResourceLineInfo, existing, isConditionTrue, subscriptionId, resourceGroupName, scope, resourceId, referenceApiVersion, isTemplateResource, isAction, provisioningOperation'.'",
        "additionalInfo": [
            {
                "type": "TemplateViolation",
                "info": {
                    "lineNumber": 47,
                    "linePosition": 5,
                    "path": ""
                }
            }
        ]
    }
}

My question is, how to access existing managed identity in existing web app to add access policy in newly created key vault?

EDIT

If i add identity block to resource marked as existing i get this error:

The property "identity" cannot be used in an existing resource declaration.bicep(BCP173)


Solution

  • if the error text is correct, i'd think you need to do something like:

    reference(resourceId('Microsoft.Web/sites', 'apiWebAppName'), '2022-03-01', 'Full').identity.principalId