如何在 Azure 上创建环境变量以访问 Key Vault

How to create environment variables on Azure to access Key Vault

我想编写 Python 代码来读取存储在 Azure Key Vault 中的机密。此代码将 运行 在云上的 Azure 容器上。它是这样的:

from azure.keyvault.secrets import SecretClient
from azure.identity import DefaultAzureCredential
from azure.core.exceptions import HttpResponseError
import os


VAULT_URL = os.environ["VAULT_URL"]
credential = DefaultAzureCredential()
client = SecretClient(vault_url=VAULT_URL, credential=credential)

print("\n.. Get a Secret by name")
company_secret = client.get_secret('secret_name')
print("Secret with name '{0}' was found with value '{1}'.".format(company_secret.name, company_secret.value))

问题是,我应该指定一些环境变量,例如 Vault URL,但我不知道该怎么做。我也不知道应该将凭据放在哪里才能实际访问 Key Vault。

主要问题是:如何建立环境变量?

谢谢

环境变量只是一个字典,因此设置它们与获取它们非常相似。

# Gets env var
VAULT_URL = os.environ["VAULT_URL"] 
# Sets env var
os.environ['URL_VAULT'] = 'Some value'

您可能希望在覆盖之前验证它们不存在:

if 'URL_VAULT' not in os.environ:
    os.environ['URL_VAULT'] = 'Some value'