首页 > 解决方案 > 在 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}')

标签: pythonazureazure-keyvault

解决方案


好吧,对象可能是 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_IDand 。ALLOW_TENANT_IDobjectIdtenantId


推荐阅读