Azure Key Vault
đThis blog post aims to guide you through the process of configuring a Python application to access information from the Azure Key Vault using the CLI.
đRun the below command to create the Resource group.
az group create --name "cnlrg" -l "EastUS"
az keyvault create --name "<cnlkeyvault>" -g "cnlrg"
đCreate the key vault using the below syntax.
đLetâs generate a secret named âcnlSecretâ with the value âSuccess!â. Add the secret to the newly created key vault using the below command.
az keyvault secret set --vault-name "<cnlkeyvault>" --name "cnlSecret" --value "Success!"
đCreate a Linux Virtual machine.
az vm create \
--resource-group cnlrg \
--name cnlVM \
--image UbuntuLTS \
--admin-username cnluser \
--generate-ssh-keys
đTake note of the âpublicIpAddressâ value in the output.
đThe âaz vm identity assignâ command is used to create a system-assigned identity for the virtual machine.
az vm identity assign --name "cnlVM" --resource-group "cnlrg"
đTake note of the system-assigned identity.
đNext, I will grant the permissions of the identity that was created to my key vault using the below command.
az keyvault set-policy --name "cnlkeyvault" --object-id "<systemAssignedIdentity>" --secret-permissions get list
đLetâs login to the VM using ssh.
đssh username@<IP address>.
đOn the virtual machine, check the existing Python libraries.
python3 --version
pip3 --version -pip
đPip3 will throw an error âthe library doesnât existâ, so install pip3 libraries.
sudo apt update
sudo apt install python3-pip
đNow we will install two libraries like key vault secrets and azure. identity that will be used in our Python script.
pip3 install azure-keyvault-secrets
đWhile installing Azure. identity, you will find the below error.
đI researched the issue and found the below commands are useful to fix it.
pip3 install --upgrade pip
pip3 install cryptography
đRerun the identity command; this time it should work fine.
pip3 install azure.identity
đNow I will create a Python script to read the secret from the Key Vault.
sample.py
from azure.keyvault.secrets import SecretClient
from azure.identity import DefaultAzureCredential
key_vault_name = "cnlkeyvault"
key_vault_uri = f"https://{key_vault_name}.vault.azure.net"
secret_name = "cnlSecret"
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 script to check if it is working fine.
python3 sample.py
đSuccessfully retrieved the secret from the Key Vault.
đClean up the Resource group.
az group delete -g cnlrg
Thank you, thatâs all for today. See you in the next blog đ