快速入门:适用于 Python 的 Azure Key Vault 机密客户端库Quickstart: Azure Key Vault secrets client library for Python

适用于 Python 的 Azure Key Vault 客户端库入门。Get started with the Azure Key Vault client library for Python. 请遵循以下步骤安装包并试用基本任务的示例代码。Follow the steps below to install the package and try out example code for basic tasks. 通过使用 Key Vault 存储机密,可以避免在代码中存储机密,从而提高应用程序的安全性。By using Key Vault to store secrets, you avoid storing secrets in your code, which increases the security of your app.

API 参考文档 | 库源代码 | 包(Python 包索引)API reference documentation | Library source code | Package (Python Package Index)

设置本地环境Set up your local environment

  1. 请确保你具有活动订阅的 Azure 帐户Make sure you have an Azure account with an active subscription.

  2. 安装 Python 2.7+ 或 3.5.3+Install Python 2.7+ or 3.5.3+.

  3. 安装 Azure CLIInstall the Azure CLI.

  4. 按照为本地开发配置身份验证的说明操作,使用该说明创建本地服务主体,并通过环境变量将其提供给 Python 的 Azure Key Vault 客户端。Follow the instructions on Configure authentication for local development, with which you create a local service principal and make it available to the Azure Key Vault Client for Python through environment variables.

    直接在 Azure 上运行代码时,如果应用使用托管标识,则不需要单独的服务主体。When running code directly on Azure, a separate service principal is not needed if the app uses managed identity.

  5. 在终端或命令提示符中,创建合适的项目文件夹,然后创建并激活 Python 虚拟环境,如使用 Python 虚拟环境中所述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

  6. 安装 Azure Active Directory 标识库:Install the Azure Active Directory identity library:

    pip install azure.identity
    
  1. 安装 Key Vault 机密库:Install the Key Vault secrets library:

    pip install azure-keyvault-secrets
    

创建资源组和 Key VaultCreate a resource group and key vault

  1. 使用 az group create 命令以创建资源组:Use the az group create command to create a resource group:

    az group create --name KeyVault-PythonQS-rg --location chinaeast
    

    如果愿意,你可以将“chinaeast”更改为离你更近的位置。You can change "chinaeast" to a location nearer to you, if you prefer.

  2. 使用 az keyvault create 创建密钥保管库:Use az keyvault create to create the key vault:

    az keyvault create --name <your-unique-keyvault-name> --resource-group KeyVault-PythonQS-rg
    

    <your-unique-keyvault-name> 替换为在整个 Azure 中均唯一的名称。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.

  3. 创建用于向代码提供 Key Vault 名称的环境变量:Create an environment variable that supplies the name of the Key Vault to the code:

    set KEY_VAULT_NAME=<your-unique-keyvault-name>
    

为服务主体授予对 Key Vault 的访问权限Give the service principal access to your key vault

运行以下 az keyvault set-policy 命令,以授权服务主体对机密进行获取、列出和设置操作。Run the following az keyvault set-policy command to authorize your service principal for get, list, and set operations on secrets. 此命令依赖前面步骤中创建的 KEY_VAULT_NAMEAZURE_CLIENT_ID 环境变量。This command relies on the KEY_VAULT_NAME and AZURE_CLIENT_ID environment variables created in previous steps.

az keyvault set-policy --name %KEY_VAULT_NAME% --spn %AZURE_CLIENT_ID% --resource-group KeyVault-PythonQS-rg --secret-permissions delete get list set 

此命令依赖前面步骤中创建的 KEY_VAULT_NAMEAZURE_CLIENT_ID 环境变量。This command relies on the KEY_VAULT_NAME and AZURE_CLIENT_ID environment variables created in previous steps.

有关详细信息,请参阅分配访问策略 - CLIFor more information, see Assign an access policy - CLI

创建示例代码Create the sample code

使用适用于 Python 的 Azure Key Vault 客户端库,可以管理机密和相关的资产(例如证书和加密密钥)。The Azure Key Vault client library for Python allows you to manage secrets and related assets such as certificates and cryptographic keys. 以下代码示例演示如何创建客户端以及设置、检索和删除机密。The following code sample demonstrates how to create a client, set a secret, retrieve a secret, and delete a secret.

创建包含此代码的名为 kv_secrets.py 的文件。Create a file named kv_secrets.py that contains this code.

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

keyVaultName = os.environ["KEY_VAULT_NAME"]
KVUri = f"https://{keyVaultName}.vault.azure.cn"

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

确保上一部分中的代码位于名为 kv_secrets.py 的文件中。Make sure the code in the previous section is in a file named kv_secrets.py. 然后,使用以下命令运行代码:Then run the code with the following command:

python kv_secrets.py
  • 如果遇到权限错误,请确保已运行 az keyvault set-policy 命令If you encounter permissions errors, make sure you ran the az keyvault set-policy command.
  • 重新运行具有相同机密名称的代码可能会产生错误:“(冲突)机密 当前处于已删除但可恢复的状态。”Re-running the code with the same secrete name may produce the error, "(Conflict) Secret is currently in a deleted but recoverable state." 请使用另一机密名称。Use a different secret name.

代码详细信息Code details

进行身份验证并创建客户端Authenticate and create a client

在前面的代码中,DefaultAzureCredential 对象使用针对服务主体创建的环境变量。In the preceding code, the DefaultAzureCredential object uses the environment variables you created for your service principal. 每当从 Azure 库创建客户端对象(例如 SecretClient)以及要通过该客户端使用的资源的 URI 时,都要提供此凭据:You provide this credential whenever you create a client object from an Azure library, such as SecretClient, along with the URI of the resource you want to work with through that client:

credential = DefaultAzureCredential()
client = SecretClient(vault_url=KVUri, credential=credential)

保存机密Save a secret

获取密钥保管库的客户端对象后,可以使用 set_secret 方法来存储机密:Once you've obtained the client object for the key vault, you can store a secret using the set_secret method:

client.set_secret(secretName, secretValue)

调用 set_secret 会生成对密钥保管库的 Azure REST API 的调用。Calling set_secret generates a call to the Azure REST API for the key vault.

在处理请求时,Azure 使用你提供给客户端的凭据对象,对调用方的标识(服务主体)进行身份验证。When handling the request, Azure authenticates the caller's identity (the service principal) using the credential object you provided to the client.

它还将检查调用方是否有权执行请求的操作。It also checks that the caller is authorized to perform the requested action. 先前使用 az keyvault set-policy 命令向服务主体授予了此授权。You granted this authorization to the service principal earlier using the az keyvault set-policy command.

检索机密Retrieve a secret

若要从 Key Vault 读取机密,请使用 get_secret 方法:To read a secret from Key Vault, use the get_secret method:

retrieved_secret = client.get_secret(secretName)

机密值包含在 retrieved_secret.value 中。The secret value is contained in retrieved_secret.value.

还可以使用 Azure CLI 命令 az keyvault secret show 来检索机密。You can also retrieve a secret with the the Azure CLI command az keyvault secret show.

删除机密Delete a secret

若要删除机密,请使用 begin_delete_secret 方法:To delete a secret, use the begin_delete_secret method:

poller = client.begin_delete_secret(secretName)
deleted_secret = poller.result()

begin_delete_secret 方法是异步方法,将返回一个轮询器对象。The begin_delete_secret method is asynchronous and returns a poller object. 调用轮询器的 result 方法等待其完成。Calling the poller's result method waits for its completion.

可以使用 Azure CLI 命令 az keyvault secret show 来验证是否删除了机密。You can verify that the secret had been removed with the Azure CLI command az keyvault secret show.

删除机密后,该机密会在一段时间内保持已删除但可恢复状态。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

如果还想进行证书密钥相关试验,可以重复使用在本文中创建的 Key Vault。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:

az group delete --resource-group KeyVault-PythonQS-rg

后续步骤Next steps