Introduction

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.

Pre-requisite

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 https://www.python.org/downloads/)

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 ‘test.py’ python script file with the following content:
from azure.keyvault import KeyVaultClient
from msrestazure.azure_active_directory import MSIAuthentication

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

Conclusion

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.

References

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 “test.py”, line 1, in <module>
      from azure.keyvault import KeyVaultClient
    ImportError: cannot import name KeyVaultClient

    Is there something i am missing ?

    Thanks

    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 https://github.com/Azure/azure-sdk-for-python/issues/8591#issuecomment-554384010 for how to work with the more recent version.

      1. judith Francis

        Thank you 🙂

Leave a Comment