Search code examples
azureazure-sdk-python

Azure: Python SDK and KeyVault -- Service Principal


I am unclear as to how I should establish a service principal following the guide laid out here: https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/keyvault/azure-keyvault-secrets/README.md#create-a-service-principal-optional

I have an Azure App Service (Web App) that is loaded with a docker image. This App Service also has an app registration tied to it for authentication.

I can execute the code: az ad sp create-for-rbac --name http://my-application --skip-assignment against three potential targets:

  • My Azure App Service web app name
  • My Azure AD App Registration name
  • A completely new name

What do I select and why?

Later in the guide, it asks that three environmental variables be set like so:

export AZURE_CLIENT_ID="generated app id"
export AZURE_CLIENT_SECRET="random password"
export AZURE_TENANT_ID="tenant id"

Can these be set within my Azure App Service web app Configuration -> Application Settings? Or must they be set in my Dockerfile?


Solution

  • If you want to access an Azure Key Vault from an Azure Web App for Containers in Python, the recommended way is to use Managed Identity instead of creating and managing your own Service Principal. Managed Identity is supported in Web App for Containers.

    In the Python container, you can access the Azure Key Vault secret using the managed identity with the following lines of code

    from azure.keyvault.secrets import SecretClient
    from azure.identity import DefaultAzureCredential
    
    credentials = DefaultAzureCredential()
    client = SecretClient("https://yourkeyvault.vault.azure.net/", credentials)
    secret = client.get_secret("yoursecretname").value
    

    That way you don't have to store any service principal secret, neither in the container nor as environment variables. DefaultAzureCredential() will try to call a managed identity service provided by Microsoft which is available within your app service and can be used to create a token that is in turn used to authenticate against the Key Vault.

    Afterwards, build your Python image and upload it to a container registry. Then reference the image when creating your app service.

    az webapp create --resource-group <resoure group name> --plan <app service plan name> --name <app name> --deployment-container-image-name <container registry name>.azurecr.io/<image name>
    

    Next go to your created app service > Identity and turn system-assigned managed identity on

    enter image description here

    You'll get an object ID of the created service principal. In you Key Vault go to "Access policies" and add this object ID with the permissions you need (assuming that you need to get a secret out of the vault in this example)

    enter image description here

    You should now be able to retrieve secrets from Azure Key Vault.