使用 Azure Key Vault 获取机密

Use Azure Key Vault to get secrets

我想在 ML 笔记本中使用 Azure Key Vault 来检索机密。我遵循的教程 here 建议使用

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

vault_url = 'https://<myvaulturl>.vault.azure.net'
az_credential = DefaultAzureCredential()
client = SecretClient(vault_url=vault_url, credential=az_credential)

client.get_secret('<mysecret>')

但是我得到这个错误 ClientAuthenticationError: DefaultAzureCredential failed to retrieve a token from the included credentials. Attempted credentials: EnvironmentCredential: EnvironmentCredential authentication unavailable. Environment variables are not fully configured. ManagedIdentityCredential: Unexpected response 'None'
我认为这确实取决于我没有设置环境变量这一事实:

AZURE_CLIENT_ID
AZURE_CLIENT_SECRET
AZURE_TENANT_ID

我想知道是否有任何其他方法可以在不使用 DefaultAzureCredential class 的情况下访问保管库。
有人知道吗?

尝试使用 ClientSecretCredential 来做到这一点:

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

AZURE_TENANT_ID = ''
AZURE_CLIENT_ID = ''
AZURE_CLIENT_SECRET = ''


cred = ClientSecretCredential(
    client_id = AZURE_CLIENT_ID,
    client_secret = AZURE_CLIENT_SECRET,
    tenant_id = AZURE_TENANT_ID
)

keyVaultName = ''
KVUri = f"https://{keyVaultName}.vault.azure.net"

sc = SecretClient(vault_url=KVUri, credential=cred)
print(sc.get_secret('<secret name>').value)

结果:

更新:

  1. 您可以在 Azure 门户上找到您的租户 ID:

  1. 跟随this doc to create an Azure AD app and follow this section创建一个应用秘密。这样您就拥有了 ClientSecretCredential

    的所有 3 个参数(租户 ID、客户端 ID 和客户端密码)
  2. 按照 this doc 将此应用程序添加到访问策略,以便此应用程序有权查询 Azure Key vault 中的机密。