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:
- Azure VM
- Azure Key Vault
- Python is already installed in the Azure VM (can be downloaded at https://www.python.org/downloads/)
The steps
-
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)
-
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“
-
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.
- 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)
- 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
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
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.
Thank you 🙂