This is a walk-through showing how to use System Managed Service Identity (MSI) from an Azure VM to retrieve an Azure Key Vault secret in python.


To use the steps in this walk-through you need to have the following:

  1. Azure VM
  2. Azure Key Vault
  3. Python is already installed in the Azure VM (can be downloaded at

The steps

  1. Enable System MSI for the Azure VM in the Azure portal (on the selected Azure VM blade -> Go to the Identity section -> change the Status to ‘On’ in the System assigned tab -> Save)

  2. Install Azure Key Vault for python in the Azure VM

    RDP to the Azure Key Vault machine and open a command line and run “pip install azure-keyvault

  3. Configure the System MSI to have access to your Azure Key Vault in the Azure portal (from the selected Azure Key vault -> Access policies -> Add new)

    In the ‘Select principal’ section select the Azure VM MSI that you just created in step 1 above. The MSI has the same name as the Azure VM. Also remember to give appropriate permissions (Key permissions, secret permissions, and certificate permissions) to the MSI depending on what you want to do with the MSI. In this walk-through I’ll use the MSI to retrieve the secret so it’s sufficient to give just give ‘Get’ access in the secret permissions section.

  1. Create a ‘’ python script file with the following content:
from azure.keyvault import KeyVaultClient
from msrestazure.azure_active_directory import MSIAuthentication

credentials = MSIAuthentication(resource='')
kvclient = KeyVaultClient(credentials)
res = kvclient.get_secret("https://<vault name>", "<secret name>", "").value
  1. Run the above script and you should get your secret value printed out


The above step demonstrates a simple way to use System MSI to retrieve an Azure Key Vault secret. The script use the MSIAuthentication class for MSI authentication to Azure AD and get an access token for Azure key vault.


How to use managed identities for Azure resources on an Azure VM with Azure SDKs

Azure Key Vault Developer’s Guide

3 Thoughts to “Retrieving Azure Key Vault Secret using System MSI in an Azure VM in Python”

  1. judith Francis

    I am getting this following error.
    File “”, line 1, in <module>
      from azure.keyvault import KeyVaultClient
    ImportError: cannot import name KeyVaultClient

    Is there something i am missing ?


    1. Bac Hoang [MSFT]

      Hi Judith,
      The KeyVaultClient class is available in azure-keyvault package v1.1. It’s not available in the more recent version. Take a look at for how to work with the more recent version.

      1. judith Francis

        Thank you 🙂

Leave a Comment