Quickstart: Azure Key Vault secret client library for Python
Article
Get started with the Azure Key Vault secret client library for Python. Follow these steps to install the package and try out example code for basic tasks. By using Key Vault to store secrets, you avoid storing secrets in your code, which increases the security of your app.
This quickstart is using Azure Identity library with Azure CLI or Azure PowerShell to authenticate user to Azure Services. Developers can also use Visual Studio or Visual Studio Code to authenticate their calls, for more information, see Authenticate the client with Azure Identity client library.
If the CLI can open your default browser, it will do so and load an Azure sign-in page.
Otherwise, open a browser page at https://aka.ms/devicelogin and enter the
authorization code displayed in your terminal.
Sign in with your account credentials in the browser.
Run the Connect-AzAccount command.
Azure PowerShell
Connect-AzAccount
If PowerShell can open your default browser, it will do so and load an Azure sign-in page.
Otherwise, open a browser page at https://aka.ms/devicelogin and enter the
authorization code displayed in your terminal.
Sign in with your account credentials in the browser.
Install the packages
In a terminal or command prompt, create a suitable project folder, and then create and activate a Python virtual environment as described on Use Python virtual environments.
Use the az group create command to create a resource group:
Azure CLI
az group create --name myResourceGroup --location eastus
You can change "eastus" to a location nearer to you, if you prefer.
Use az keyvault create to create the key vault:
Azure CLI
az keyvault create --name<your-unique-keyvault-name>--resource-group myResourceGroup
Replace <your-unique-keyvault-name> with a name that's unique across all of Azure. You typically use your personal or company name along with other numbers and identifiers.
Use the New-AzResourceGroup command to create a resource group:
Replace <your-unique-keyvault-name> with a name that's unique across all of Azure. You typically use your personal or company name along with other numbers and identifiers.
Set the KEY_VAULT_NAME environmental variable
Our script will use the value assigned to the KEY_VAULT_NAME environment variable as the name of the key vault. You must therefore set this value using the following command:
az role assignment create --role"Key Vault Secrets Officer"--assignee"<upn>"--scope"/subscriptions/<subscription-id>/resourceGroups/<resource-group-name>/providers/Microsoft.KeyVault/vaults/<your-unique-keyvault-name>"
Replace <upn>, <subscription-id>, <resource-group-name> and <your-unique-keyvault-name> with your actual values. Your UPN will typically be in the format of an email address (e.g., username@domain.com).
Create the sample code
The Azure Key Vault secret client library for Python allows you to manage secrets. The following code sample demonstrates how to create a client, set a secret, retrieve a secret, and delete a secret.
Create a file named kv_secrets.py that contains this code.
Python
import os
from azure.keyvault.secrets import SecretClient
from azure.identity import DefaultAzureCredential
keyVaultName = os.environ["KEY_VAULT_NAME"]
KVUri = f"https://{keyVaultName}.vault.azure.net"
credential = DefaultAzureCredential()
client = SecretClient(vault_url=KVUri, credential=credential)
secretName = input("Input a name for your secret > ")
secretValue = input("Input a value for your secret > ")
print(f"Creating a secret in {keyVaultName} called '{secretName}' with the value '{secretValue}' ...")
client.set_secret(secretName, secretValue)
print(" done.")
print(f"Retrieving your secret from {keyVaultName}.")
retrieved_secret = client.get_secret(secretName)
print(f"Your secret is '{retrieved_secret.value}'.")
print(f"Deleting your secret from {keyVaultName} ...")
poller = client.begin_delete_secret(secretName)
deleted_secret = poller.result()
print(" done.")
Run the code
Make sure the code in the previous section is in a file named kv_secrets.py. Then run the code with the following command:
Rerunning the code with the same secret name may produce the error, "(Conflict) Secret <name> is currently in a deleted but recoverable state." Use a different secret name.
Code details
Authenticate and create a client
Application requests to most Azure services must be authorized. Using the DefaultAzureCredential class provided by the Azure Identity client library is the recommended approach for implementing passwordless connections to Azure services in your code. DefaultAzureCredential supports multiple authentication methods and determines which method should be used at runtime. This approach enables your app to use different authentication methods in different environments (local vs. production) without implementing environment-specific code.
In this quickstart, DefaultAzureCredential authenticates to key vault using the credentials of the local development user logged into the Azure CLI. When the application is deployed to Azure, the same DefaultAzureCredential code can automatically discover and use a managed identity that is assigned to an App Service, Virtual Machine, or other services. For more information, see Managed Identity Overview.
In the example code, the name of your key vault is expanded using the value of the KVUri variable, in the format: "https://<your-key-vault-name>.vault.azure.net".
Once deleted, a secret remains in a deleted but recoverable state for a time. If you run the code again, use a different secret name.
Clean up resources
If you want to also experiment with certificates and keys, you can reuse the Key Vault created in this article.
Otherwise, when you're finished with the resources created in this article, use the following command to delete the resource group and all its contained resources: