python - 在 Python 中创建 Azure 密钥保管库
问题描述
我正在尝试使用本教程(https://docs.microsoft.com/en-us/python/api/overview/azure/key-vault?view=azure-python)以编程方式在 python 中创建密钥库。直到我调用 client.vaults.create_or_update() 时它抛出异常的最后一步之前没有错误,因为我可能没有为 ALLOW_OBJECT_ID 和 ALLOW_TENANT_ID 使用正确的值。文档说可以在门户网站上找到这些值,但我找不到它,有没有办法以编程方式获取它?
错误:srest.exceptions.AuthenticationError: , AdalError: Get Token request returned http error: 400 and server response: {"error":"unauthorized_client","error_description":"AADSTS700016: Application with identifier XXX is not found in the directory YY
代码:
import subprocess
import json
from azure.mgmt.keyvault import KeyVaultManagementClient
from azure.common.credentials import ServicePrincipalCredentials
def get_subscription():
subs = json.loads(subprocess.check_output('az account list',
shell=True).decode('utf-8'))
subscription = subs[1]['id']
cmd = 'az ad sp create-for-rbac --role="Contributor" --scopes="/subscriptions/%s"' % subscription
creds = json.loads(subprocess.check_output(cmd, shell=True).decode('utf-8'))
return subscription, creds
def create_key_vault(vault_name='TestKeyVault'):
subscription_id, creds = get_subscription()
client_id = creds['appId']
secret = creds['password']
tenant = creds['tenant']
credentials = ServicePrincipalCredentials(client_id=client_id, secret=secret, tenant=tenant)
client = KeyVaultManagementClient(credentials, subscription_id)
ALLOW_OBJECT_ID = client_id
ALLOW_TENANT_ID = tenant
RESOURCE_GROUP = 'SomeRG'
VAULT_NAME = vault_name
# Vault properties may also be created by using the
# azure.mgmt.keyvault.models.VaultCreateOrUpdateParameters
# class, rather than a map.
operation = client.vaults.create_or_update(
RESOURCE_GROUP,
VAULT_NAME,
{
'location': 'eastus',
'properties': {
'sku': {
'name': 'standard'
},
'tenant_id': ALLOW_TENANT_ID,
'access_policies': [{
'object_id': ALLOW_OBJECT_ID,
'tenant_id': ALLOW_TENANT_ID,
'permissions': {
'keys': ['all'],
'secrets': ['all']
}
}]
}
}
)
vault = operation.result()
print(f'New vault URI: {vault.properties.vault_uri}')
解决方案
好吧,对象可能是 Azure AD 租户中的用户、安全组、服务主体,如果您不熟悉 keyvault 中的访问策略,请查看此文档。
要以语法方式获取它们,最简单的方法是在 python 中使用 Azure CLI。
用于az account show
获取tenantId
.
用于az ad user list
获取objectId
用户的。
用于az ad group list
获取objectId
安全组的。
用于az ad sp list
获取objectId
服务主体的。
然后你应该用你需要的和上面的任何东西来指定ALLOW_OBJECT_ID
and 。ALLOW_TENANT_ID
objectId
tenantId
推荐阅读
- vue.js - 带有 3rd 方 Web API 令牌管理的 VueJS
- angular - 如何在 angluar11 中使用 lottie-web?
- android - Android 10及以上系统如何获取共享存储文件夹的文件路径?
- c - 我的 C 代码有问题。它返回非零值,我不知道为什么
- javascript - 如何在 JavaScript 的构造函数中使用模板文字
- linux - qmake:没有这样的文件或目录(TI 工具链)
- python - Python 使用 os ping 很多站点
- windows - 有没有办法在 desktop.ini 文件中使用 IconResource 路径中的文件夹名称?
- r-corrplot - corrplot 中的 Potentiel 错误;当 insig = "blank" 时相关系数不可见
- rest - 如果唯一可用的过滤器是“afterDate”过滤器,我应该使用什么策略逐片获取 API 的数据?