(SubscriptionNotFound) 找不到订阅 'subscriptions'

(SubscriptionNotFound) The subscription 'subscriptions' could not be found

我列出了所有可用的订阅。调用 subscription.id 时 returns:

/subscriptions/<subscription-id>

现在,如果我尝试将它直接传递给 Azure 计算库,它不会接受它作为 ID。

compute_client = ComputeManagementClient(credential=credentials, subscription_id=subscription.id)

>> (SubscriptionNotFound) The subscription 'subscriptions' could not be found.

这意味着我必须手动清理 ID

subscription.id.replace("/subscription/", "")

这很恶心。是否有仅获取 ID 的内置方法?

不幸的是,没有内置方法可以通过python获取订阅ID。

您可以像 (Get-AzSubscription).SubscriptionId 一样使用 power shell 命令。

来自 calling power shell command from Python:

The subprocess module is a module in Python standard library. It consists of the call method which can be used to create new processes and receive there return values and error codes/

To run a powershell command you just pass the command name to the call method as a string.

import subprocess 
subprocess.call("(Get-AzSubscription).SubscriptionId")

这是 subscription_id 属性: https://docs.microsoft.com/en-us/python/api/azure-mgmt-resource/azure.mgmt.resource.subscriptions.v2019_11_01.models.subscription?view=azure-python

from azure.mgmt.resource.subscriptions import SubscriptionClient
client = SubscriptionClient(credential)

for sub in client.subscriptions.list():
     print(sub.subscription_id)

(免责声明我在微软的 Azure SDK 团队工作)