Quickstart: Azure Key Vault biblioteca secreta de clientes para PythonQuickstart: Azure Key Vault secret client library for Python
Começa com a biblioteca secreta do Azure Key Vault para python.Get started with the Azure Key Vault secret client library for Python. Siga os passos abaixo para instalar a embalagem e experimente o código de exemplo para tarefas básicas.Follow the steps below to install the package and try out example code for basic tasks. Ao utilizar o Key Vault para armazenar segredos, evita guardar segredos no seu código, o que aumenta a segurança da sua aplicação.By using Key Vault to store secrets, you avoid storing secrets in your code, which increases the security of your app.
Documentação de | referência da API Código fonte da biblioteca | Pacote (Índice de Pacote Python)API reference documentation | Library source code | Package (Python Package Index)
Pré-requisitosPrerequisites
- Uma subscrição Azure - crie uma gratuitamente.An Azure subscription - create one for free.
- Python 2.7+ ou 3.5.3+Python 2.7+ or 3.5.3+
- CLI do AzureAzure CLI
Este quickstart pressupõe que está a executar o Azure CLI numa janela do terminal Linux.This quickstart assumes you are running Azure CLI in a Linux terminal window.
Configurar o ambiente localSet up your local environment
Este quickstart está a utilizar a biblioteca Azure Identity com o Azure CLI para autenticar o utilizador nos Serviços Azure.This quickstart is using Azure Identity library with Azure CLI to authenticate user to Azure Services. Os desenvolvedores também podem usar o Visual Studio ou Visual Studio Code para autenticar as suas chamadas, para obter mais informações, ver Autenticar o cliente com a biblioteca de clientes da Azure Identity.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.
Iniciar sessão no AzureSign in to Azure
Execute o comando
login
.Run thelogin
command.az login
Se o CLI conseguir abrir o seu navegador predefinido, fá-lo-á e carregará uma página de inscrição do Azure.If the CLI can open your default browser, it will do so and load an Azure sign-in page.
Caso contrário, abra uma página do navegador https://aka.ms/devicelogin e introduza o código de autorização exibido no seu terminal.Otherwise, open a browser page at https://aka.ms/devicelogin and enter the authorization code displayed in your terminal.
Inicie sessão com as credenciais da sua conta no browser.Sign in with your account credentials in the browser.
Instalar as embalagensInstall the packages
Num terminal ou pedido de comando, crie uma pasta de projeto adequada e, em seguida, crie e ative um ambiente virtual Python como descrito em ambientes virtuais Use 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.
Instalar a biblioteca de identidade do Diretório Ativo Azure:Install the Azure Active Directory identity library:
pip install azure-identity
Instale a biblioteca de segredos do Cofre de Chaves:Install the Key Vault secrets library:
pip install azure-keyvault-secrets
Criar um grupo de recursos e cofre chaveCreate a resource group and key vault
Utilize o
az group create
comando para criar um grupo de recursos:Use theaz group create
command to create a resource group:az group create --name KeyVault-PythonQS-rg --location eastus
Pode mudar o "Eastus" para um local mais próximo de si, se preferir.You can change "eastus" to a location nearer to you, if you prefer.
Utilize
az keyvault create
para criar o cofre da chave:Useaz keyvault create
to create the key vault:az keyvault create --name <your-unique-keyvault-name> --resource-group KeyVault-PythonQS-rg
Substitua
<your-unique-keyvault-name>
por um nome único em todo o Azure.Replace<your-unique-keyvault-name>
with a name that's unique across all of Azure. Normalmente, usa o seu nome pessoal ou da empresa juntamente com outros números e identificadores.You typically use your personal or company name along with other numbers and identifiers.Crie uma variável ambiental que forneça o nome do Cofre chave ao código:Create an environment variable that supplies the name of the Key Vault to the code:
Conceder acesso ao seu cofre chaveGrant access to your key vault
Crie uma política de acesso para o seu cofre-chave que concede permissão secreta à sua conta de utilizador.Create an access policy for your key vault that grants secret permission to your user account.
az keyvault set-policy --name <YourKeyVaultName> --upn user@domain.com --secret-permissions delete get list set
Definir variáveis de ambienteSet environment variables
Esta aplicação está a usar o nome do cofre como uma variável ambiental chamada KEY_VAULT_NAME
.This application is using key vault name as an environment variable called KEY_VAULT_NAME
.
WindowsWindows
set KEY_VAULT_NAME=<your-key-vault-name>
Windows PowerShellWindows PowerShell
$Env:KEY_VAULT_NAME="<your-key-vault-name>"
macOS ou LinuxmacOS or Linux
export KEY_VAULT_NAME=<your-key-vault-name>
Criar o código de amostraCreate the sample code
A biblioteca secreta do Azure Key Vault para Python permite-lhe gerir segredos.The Azure Key Vault secret client library for Python allows you to manage secrets. A seguinte amostra de código demonstra como criar um cliente, estabelecer um segredo, recuperar um segredo e apagar um segredo.The following code sample demonstrates how to create a client, set a secret, retrieve a secret, and delete a secret.
Crie um ficheiro chamado kv_secrets.py que contenha este código.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.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.")
Executar o códigoRun the code
Certifique-se de que o código na secção anterior está num ficheiro denominado kv_secrets.py.Make sure the code in the previous section is in a file named kv_secrets.py. Em seguida, executar o código com o seguinte comando:Then run the code with the following command:
python kv_secrets.py
- Se encontrar permissões, certifique-se de que executou o
az keyvault set-policy
comando.If you encounter permissions errors, make sure you ran theaz keyvault set-policy
command. - Re-executar o código com o mesmo nome secreto pode produzir o erro, "(Conflito) Segredo
está atualmente em um estado apagado, mas recuperável." Re-running the code with the same secrete name may produce the error, "(Conflict) Secretis currently in a deleted but recoverable state." Use um nome secreto diferente.Use a different secret name.
Detalhes do códigoCode details
Autenticar e criar um clienteAuthenticate and create a client
Neste arranque rápido, o utilizador com sessão é utilizado para autenticar o cofre de chaves, que é o método preferido para o desenvolvimento local.In this quickstart, logged in user is used to authenticate to key vault, which is preferred method for local development. Para aplicações implantadas no Azure, a identidade gerida deve ser atribuída ao Serviço de Aplicações ou Máquina Virtual, para obter mais informações, consulte a Visão Geral da Identidade Gerida.For applications deployed to Azure, managed identity should be assigned to App Service or Virtual Machine, for more information, see Managed Identity Overview.
Por exemplo, o nome do seu cofre-chave é expandido para o cofre uri chave, no formato "https:// <your-key-vault-name> .vault.azure.net".In below example, the name of your key vault is expanded to the key vault URI, in the format "https://<your-key-vault-name>.vault.azure.net". Este exemplo está a usar a classe 'DefaultAzureCredential()' que permite usar o mesmo código em diferentes ambientes com diferentes opções para fornecer identidade.This example is using 'DefaultAzureCredential()' class, which allows to use the same code across different environments with different options to provide identity. Para mais informações, consulte a Autenticação Credencial Azure Padrão.For more information, see Default Azure Credential Authentication.
credential = DefaultAzureCredential()
client = SecretClient(vault_url=KVUri, credential=credential)
Salvar um segredoSave a secret
Assim que tiver obtido o objeto do cliente para o cofre da chave, pode armazenar um segredo utilizando o método 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)
A chamada set_secret
gera uma chamada para a AZure REST API para o cofre chave.Calling set_secret
generates a call to the Azure REST API for the key vault.
Ao lidar com o pedido, a Azure autentica a identidade do autor da chamada (o principal do serviço) utilizando o objeto de credencial que forneceu ao cliente.When handling the request, Azure authenticates the caller's identity (the service principal) using the credential object you provided to the client.
Recuperar um segredoRetrieve a secret
Para ler um segredo do Key Vault, use o método get_secret:To read a secret from Key Vault, use the get_secret method:
retrieved_secret = client.get_secret(secretName)
O valor secreto está contido em retrieved_secret.value
.The secret value is contained in retrieved_secret.value
.
Você também pode recuperar um segredo com o azure CLI comando az keyvault show secreto.You can also retrieve a secret with the the Azure CLI command az keyvault secret show.
Eliminar um segredoDelete a secret
Para eliminar um segredo, utilize o método begin_delete_secret:To delete a secret, use the begin_delete_secret method:
poller = client.begin_delete_secret(secretName)
deleted_secret = poller.result()
O begin_delete_secret
método é assíncrona e devolve um objeto poller.The begin_delete_secret
method is asynchronous and returns a poller object. Chamar o método do poller result
espera pela sua conclusão.Calling the poller's result
method waits for its completion.
Pode verificar se o segredo foi removido com o comando Azure CLI az keyvault secret show.You can verify that the secret had been removed with the Azure CLI command az keyvault secret show.
Uma vez apagado, um segredo permanece em estado apagado, mas recuperável por um tempo.Once deleted, a secret remains in a deleted but recoverable state for a time. Se voltar a executar o código, use um nome secreto diferente.If you run the code again, use a different secret name.
Limpar os recursosClean up resources
Se também quiser experimentar certificados e chaves,pode reutilizar o Cofre-Chave criado neste artigo.If you want to also experiment with certificates and keys, you can reuse the Key Vault created in this article.
Caso contrário, quando terminar com os recursos criados neste artigo, utilize o seguinte comando para eliminar o grupo de recursos e todos os seus recursos contidos: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
Passos seguintesNext steps
- Descrição geral do cofre de chave do AzureOverview of Azure Key Vault
- Acesso seguro a um cofre de chavesSecure access to a key vault
- Guia de desenvolvedores do Azure Key VaultAzure Key Vault developer's guide
- Visão geral da segurança do Cofre de ChavesKey Vault security overview
- Autenticar com cofre de chavesAuthenticate with Key Vault