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