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

1.2k views Asked by At

I am listing all available subscriptions. When calling subscription.id it returns:

/subscriptions/<subscription-id>

Now if I try and pass that directly into say the Azure compute library it won't accept that as an ID.

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

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

This means I have to manually clean the ID

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

Which is gross. Is there an inbuilt method to get just the ID?

2

There are 2 answers

2
Laurent Mazuel On BEST ANSWER

This is the subscription_id attribute: https://learn.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)

(disclaimer I work at MS on the Azure SDK team)

2
Doris Lv On

Unfortunately, there is no inbuilt method to get subscription ID by python.

You can use power shell command like (Get-AzSubscription).SubscriptionId.

By 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")