教程:将 Azure Key Vault 与通过 Python 编写的虚拟机配合使用Tutorial: Use Azure Key Vault with a virtual machine in Python

Azure Key Vault 可帮助你保护密钥、机密和证书,例如 API 密钥和数据库连接字符串。Azure Key Vault helps you to protect keys, secrets, and certificates, such as API keys and database connection strings.

在本教程中,会设置 Python 应用程序以使用 Azure 资源的托管标识从 Azure Key Vault 读取信息。In this tutorial, you set up a Python application to read information from Azure Key Vault by using managed identities for Azure resources. 你将学习如何执行以下操作:You learn how to:

  • 创建密钥保管库Create a key vault
  • 在 Key Vault 中存储机密Store a secret in Key Vault
  • 创建一个 Azure Linux 虚拟机Create an Azure Linux virtual machine
  • 为虚拟机启用托管标识Enable a managed identity for the virtual machine
  • 授予所需的权限,让控制台应用程序从 Key Vault 读取数据Grant the required permissions for the console application to read data from Key Vault
  • 从 Key Vault 检索机密Retrieve a secret from Key Vault

在开始之前,请阅读 Key Vault 的基本概念Before you begin, read Key Vault basic concepts.

如果没有 Azure 订阅,请创建试用订阅If you don't have an Azure subscription, create a Trial Subscription.

先决条件Prerequisites

对于 Windows、Mac 和 Linux:For Windows, Mac, and Linux:

  • GitGit
  • 本教程要求在本地运行 Azure CLI。This tutorial requires that you run the Azure CLI locally. 必须安装 Azure CLI 2.0.4 或更高版本。You must have the Azure CLI version 2.0.4 or later installed. 运行 az --version 即可查找版本。Run az --version to find the version. 如果需要安装或升级 CLI,请参阅安装 Azure CLI 2.0If you need to install or upgrade the CLI, see Install Azure CLI 2.0.

登录 AzureLog in to Azure

若要使用 Azure CLI 登录到 Azure,请输入:To log in to Azure by using the Azure CLI, enter:

az  cloud  set –n  AzureChinaCloud 
az login

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

本快速入门使用预先创建的 Azure Key Vault。This quickstart uses a pre-created Azure key vault. 可以遵循 Azure CLI 快速入门Azure PowerShell 快速入门Azure 门户快速入门中的步骤创建 Key Vault。You can create a key vault by following the steps in the Azure CLI quickstart, Azure PowerShell quickstart, or Azure portal quickstart.

或者,只需运行以下 Azure CLI 或 Azure PowerShell 命令。Alternatively, you can simply run the Azure CLI or Azure PowerShell commands below.

重要

每个密钥保管库必须具有唯一的名称。Each key vault must have a unique name. 在以下示例中,将 替换为密钥保管库的名称。Replace with the name of your key vault in the following examples.

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

az keyvault create --name "<your-unique-keyvault-name>" -g "myResourceGroup"
New-AzResourceGroup -Name myResourceGroup -Location ChinaEast

New-AzKeyVault -Name "<your-unique-keyvault-name>" -ResourceGroupName "myResourceGroup" -Location "ChinaEast"

使用机密填充密钥保管库Populate your key vault with a secret

让我们创建一个名为 mySecret 的机密,其值为 Success!。Let's create a secret called mySecret, with a value of Success!. 机密可以是密码、SQL 连接字符串,或者需要安全保存的、可供应用程序使用的其他任何信息。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.

若要将机密添加到新创建的 Key Vault,请使用 Azure CLI az keyvault secret set 命令:To add a secret to your newly created key vault, use the Azure CLI az keyvault secret set command:

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

创建虚拟机Create a virtual machine

使用以下方法之一创建名为 myVM 的 VM:Create a VM called myVM using one of the following methods:

LinuxLinux WindowsWindows
Azure CLIAzure CLI Azure CLIAzure CLI
PowerShellPowerShell PowerShellPowerShell
Azure 门户Azure portal Azure 门户The Azure portal

若要使用 Azure CLI 创建 Linux VM,请使用 az vm create 命令。To create a Linux VM using the Azure CLI, use the az vm create command. 以下示例添加一个名为 azureuser 的用户帐户。The following example adds a user account named azureuser. --generate-ssh-keys 参数用来自动生成一个 SSH 密钥,并将其放置在默认密钥位置 ( ~/.ssh) 中。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 myResourceGroup \
  --name myVM \
  --image UbuntuLTS \
  --admin-username azureuser \
  --generate-ssh-keys

请记录输出中 publicIpAddress 的值。Note the value of publicIpAddress in the output.

为 VM 分配标识Assign an identity to the VM

使用 Azure CLI az vm identity assign 命令为虚拟机创建系统分配的标识:Create a system-assigned identity for the virtual machine by using the Azure CLI az vm identity assign command:

az vm identity assign --name "myVM" --resource-group "myResourceGroup"

记下以下代码中显示的系统分配的标识。Note the system-assigned identity that's displayed in the following code. 以上命令的输出为:The output of the preceding command would be:

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

为 VM 标识分配权限Assign permissions to the VM identity

现在可以运行以下命令,将前面创建的标识权限分配到 Key Vault:Now you can assign the previously created identity permissions to your key vault by running the following command:

az keyvault set-policy --name "<your-unique-keyvault-name>" --object-id "<systemAssignedIdentity>" --secret-permissions get list

登录 VMLog in to the VM

若要登录到虚拟机,请按照连接并登录到运行 Windows 的 Azure 虚拟机中的说明操作。To sign in to the virtual machine, follow the instruction Connect and sign in to an Azure virtual machine running Windows.

若要登录到 Linux VM,可以使用 ssh 命令以及在创建虚拟机步骤中提供的“”:To log into a Linux VM, you can use the ssh command with the "" given in the Create a virtual machine step:

ssh azureuser@<PublicIpAddress>

在 VM 上安装 Python 库Install Python libraries on the VM

在虚拟机上,安装将在 Python 脚本中使用的两个 Python 库:azure-keyvault-secretsazure.identityOn the virtual machine, install the two Python libraries we'll be using in our Python script: azure-keyvault-secrets and azure.identity.

例如在 Linux VM 上,可以使用 pip3 安装这些库:On a Linux VM, for instance, you can install these using pip3:

pip3 install azure-keyvault-secrets

pip3 install azure.identity

创建并编辑示例 Python 脚本Create and edit the sample Python script

在虚拟机上,创建名为 sample.py 的 Python 文件。On the virtual machine, create a Python file called sample.py. 编辑文件以包含以下代码,将“”替换为 Key Vault 的名称:Edit the file to contain the following code, replacing "" with the name of your key vault:

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

keyVaultName = "<your-unique-keyvault-name>"
KVUri = f"https://{keyVaultName}.vault.azure.cn"
secretName = "mySecret"

credential = DefaultAzureCredential()
client = SecretClient(vault_url=KVUri, credential=credential)
retrieved_secret = client.get_secret(secretName)

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

运行示例 Python 应用Run the sample Python app

最后,运行 sample.py。Lastly, run sample.py. 如果一切正常,应返回机密值:If all has gone well, it should return the value of your secret:

python3 sample.py

The value of secret 'mySecret' in '<your-unique-keyvault-name>' is: 'Success!'

清理资源Clean up resources

不再需要本教程中创建的虚拟机和 Key Vault 时,请将其删除。When they are no longer needed, delete the virtual machine and your key vault. 只需删除它们所属的资源组,即可快速执行此操作:You can do this quickly by simply deleting the resource group to which they belong:

az group delete -g myResourceGroup

后续步骤Next steps

Azure Key Vault REST APIAzure Key Vault REST API