Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List subscriptions for a given Azure account

I'm trying to list the subscriptions in an Azure account using azure-python-sdk.

I have followed this link in documentation.

https://learn.microsoft.com/en-us/python/api/azure-mgmt-subscription/azure.mgmt.subscription.operations.subscriptionsoperations?view=azure-python#list-custom-headers-none--raw-false----operation-config-


from azure.mgmt.subscription import SubscriptionClient
from msrestazure.azure_active_directory import UserPassCredentials

credentials = UserPassCredentials(username='xxxx', password='xxxx')
sub_client = SubscriptionClient(credentials)
subs = [sub.as_dict() for sub in sub_client.subscriptions.list()]
print(subs)

It is supposed to return a list of subscriptions. However, I see only empty list returned every time I try the above code. Can anybody help?

like image 554
Varun Avatar asked May 28 '19 03:05

Varun


3 Answers

Try this code,

def list_subscriptions():
    try:
        sub_client = get_client_from_cli_profile(SubscriptionClient)
    except CLIError:
        logger.info("Not logged in, running az login")
        _run_az_cli_login()
        sub_client = get_client_from_cli_profile(SubscriptionClient)

    return [["Subscription_name", "Subscription ID"]] + [
        [sub.display_name, sub.subscription_id]
        for sub in sub_client.subscriptions.list()
    ]

You can find the handy tool from here

like image 177
Sajeetharan Avatar answered Oct 21 '22 06:10

Sajeetharan


If the list is empty and you get not exception, it's likely your credentials are correct (no exception), but your user doesn't have access to subscriptions (no permissions)

In the Azure portal, in the subscription panel you have a button "Access control (IAM)" to define what users are allowed to a given subscription. https://learn.microsoft.com/azure/role-based-access-control/role-assignments-portal

https://learn.microsoft.com/azure/role-based-access-control/rbac-and-directory-admin-roles

(I work at MS in the SDK team)

like image 1
Laurent Mazuel Avatar answered Oct 21 '22 04:10

Laurent Mazuel


I think I solved the issue using Azure CLI. Yet, I still wonder why it didn't work as supposed using azure-python-sdk.

Here is the code:

import subprocess
import json
subscriptions = json.loads(subprocess.check_output('az account list', shell=True).decode('utf-8'))
print(subscriptions)

Thank you for your responses.

like image 1
Varun Avatar answered Oct 21 '22 06:10

Varun