问题
I am attempting to run this 'Retrieve a secret from the vault' example locally (Ubuntu 19.10) to retrieve a secret from an Azure Key Vault:
from azure.keyvault.secrets import SecretClient
from azure.identity import DefaultAzureCredential
client = SecretClient(vault_url="https://<<vaultname>>.vault.azure.com",
credential=DefaultAzureCredential())
secret = client.get_secret("<<mysecret>>")
However I receive the following error:
azure.core.exceptions.ClientAuthenticationError:
No credential in this chain provided a token.
Attempted credentials:
EnvironmentCredential: Incomplete environment configuration. See https://aka.ms/python-sdk-identity#environment-variables for expected environment variables
ImdsCredential: IMDS endpoint unavailable
Please visit the documentation at
https://aka.ms/python-sdk-identity#defaultazurecredential
to learn what options DefaultAzureCredential supports
The documentation on Service-to-Service authentication to Key Vault seems to suggest that I should be able to authenticate by the Azure CLI, and I've followed the steps to login via az login
, select the appropriate subscription (which I've done just in case, despite only having one), and verify access via az account get-access-token --resource https://vault.azure.net
which does return a token, however still receive the error above.
Am I wrong in assuming I should be able to authenticate after logging in via the cli?
And if so, and I need to manually set the environment variables described in the documentation link provided for EnvironmentCredential
, what values do I need to supply for AZURE_CLIENT_ID
and AZURE_CLIENT_SECRET
?
回答1:
Am I wrong in assuming I should be able to authenticate after logging in via the cli?
You're not wrong, it's possible with the current preview version of azure-identity
, 1.4.0b2 as I write this. With that installed, your code should work once you've logged in to the CLI.
... what values do I need to supply for
AZURE_CLIENT_ID
andAZURE_CLIENT_SECRET
?
These would be the client (or "application") ID of a service principal, and one of its secrets. The azure-keyvault-secrets documentation describes how to create a service principal and configure its access to a Key Vault, using the CLI.
Briefly restating that documentation here, you can create a service principal with this command:
az ad sp create-for-rbac --name http://my-application
From the output of that command, "appId" is the value of AZURE_CLIENT_ID
and "password" is the value of AZURE_CLIENT_SECRET
.
Then, to grant the service principal access to the Key Vault's secrets:
az keyvault set-policy --name <<vaultname>> --spn $AZURE_CLIENT_ID --secret-permissions get set list delete backup recover restore purge
来源:https://stackoverflow.com/questions/61125219/authenticating-to-azure-key-vault-locally-using-defaultazurecredential