Edit

Tutorial: Use Azure Key Vault with a virtual machine in Python

Azure Key Vault helps you protect keys, secrets, and certificates, such as API keys and database connection strings.

In this tutorial, you set up a Python application to read information from Azure Key Vault by using a managed identity for Azure resources. You learn how to:

  • Create a key vault
  • Store a secret in Key Vault
  • Create an Azure Linux virtual machine
  • Enable a managed identity for the virtual machine
  • Grant the required permissions for the console application to read data from Key Vault
  • Retrieve a secret from Key Vault

Before you begin, read Key Vault basic concepts.

If you don't have an Azure subscription, create a free account.

Prerequisites

For Windows, Mac, and Linux:

  • Git
  • A current version of the Azure CLI. Run az --version to check the installed version.

Sign in to Azure

Sign in to Azure with the Azure CLI:

az login

Create a resource group and key vault

This quickstart uses a precreated Azure key vault. You can create a key vault by following the steps in these quickstarts:

Alternatively, you can run these Azure CLI or Azure PowerShell commands.

Important

Each key vault must have a unique name. Replace <vault-name> with the name of your key vault in the following examples.

az group create --name "myResourceGroup" -l "EastUS"

az keyvault create --name "<vault-name>" -g "myResourceGroup" --enable-rbac-authorization true

Populate your key vault with a secret

Let's create a secret called mySecret, with a value of Success!. A secret might be a password, a SQL connection string, or any other information that you need to keep both secure and available to your application.

To add a secret to your newly created key vault, use the following command:

az keyvault secret set --vault-name "<vault-name>" --name "mySecret" --value "Success!"

Create a virtual machine

Create a VM named myVM by using one of the following methods:

Linux Windows
Azure CLI Azure CLI
PowerShell PowerShell
Azure portal Azure portal

To create a Linux VM using the Azure CLI, use the az vm create command. The following example adds a user account named azureuser. The --generate-ssh-keys parameter is used to automatically generate an SSH key, and put it in the default key location (~/.ssh).

az vm create \
  --resource-group <resource-group> \
  --name myVM \
  --image Ubuntu2204 \
  --admin-username azureuser \
  --generate-ssh-keys

Note the value of publicIpAddress in the output.

Assign an identity to the VM

Create a system-assigned managed identity for the VM by using the az vm identity assign command:

az vm identity assign --name "myVM" --resource-group "<resource-group>"

Note the system-assigned identity in the output:

{
  "systemAssignedIdentity": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
  "userAssignedIdentities": {}
}

Assign permissions to the VM identity

To gain permissions to your key vault through Role-Based Access Control (RBAC), assign a role to your "User Principal Name" (UPN) using the Azure CLI command az role assignment create.

az role assignment create --role "Key Vault Secrets User" --assignee "<upn>" --scope "/subscriptions/<subscription-id>/resourceGroups/myResourceGroup/providers/Microsoft.KeyVault/vaults/<vault-name>"

Replace <upn>, <subscription-id>, and <vault-name> with your actual values. If you used a different resource group name, replace "myResourceGroup" as well. Your UPN will typically be in the format of an email address (e.g., username@domain.com).

Sign in to the VM

To sign in to the VM, follow the instructions in Connect and sign in to an Azure virtual machine running Linux or Connect and sign in to an Azure virtual machine running Windows.

To sign in to a Linux VM, use ssh with the <public-ip-address> from the Create a virtual machine step:

ssh azureuser@<public-ip-address>

Install Python libraries on the VM

On the VM, install the two Python libraries the sample script uses: azure-keyvault-secrets and azure-identity.

On a Linux VM, install them with pip3:

pip3 install azure-keyvault-secrets azure-identity

Create and edit the sample Python script

On the VM, create a Python file named sample.py. Paste the following code into the file, replacing <vault-name> with your key vault name:

from azure.keyvault.secrets import SecretClient
from azure.identity import DefaultAzureCredential

key_vault_name = "<vault-name>"
key_vault_uri = f"https://{key_vault_name}.vault.azure.net"
secret_name = "mySecret"

credential = DefaultAzureCredential()
client = SecretClient(vault_url=key_vault_uri, credential=credential)
retrieved_secret = client.get_secret(secret_name)

print(f"The value of secret '{secret_name}' in '{key_vault_name}' is: '{retrieved_secret.value}'")

Run the sample Python app

Run sample.py. If everything is configured correctly, the app prints the secret value:

python3 sample.py

The value of secret 'mySecret' in '<vault-name>' is: 'Success!'

Clean up resources

When you no longer need them, delete the VM and the key vault. The fastest way is to delete the resource group they belong to:

az group delete -g "myResourceGroup"

Next steps

Azure Key Vault REST API