Search code examples
azureazure-sdkazure-sdk-python

How do you turn a principal_id into a username using the Azure Python SDK


Using the Azure Python SDK I'm trying to build a script that will audit our various user role authorizations. I'm able to pull a list of role assignments using the following:

authorizationClient = AuthorizationManagementClient(credential, subscription_id)
roles = authorizationClient.role_assignments.list()

This works, and I get a list of dicts that seems to have every piece of info I need except the principal_name. Example response:

{'additional_properties': {}, 'id': '/providers/Microsoft.Management/managementGroups/<group_ID>/providers/Microsoft.Authorization/roleAssignments/<role_ID>', 'name': '<role_ID>', 'type': 'Microsoft.Authorization/roleAssignments', 'scope': '/providers/Microsoft.Management/managementGroups/<scope_ID>', 'role_definition_id': '/subscriptions/<subscription_ID>/providers/Microsoft.Authorization/roleDefinitions/<role_def_id>', 'principal_id': '<principal_ID>', 'principal_type': 'Group', 'can_delegate': None}

Using the Azure Python SDK, is there a way to look up a principal_name given a principal_id?

I've been reading through the SDK documentation for a few hours now and can't seem to find the answer. All I can find is that the azure cli spits out the principal_id and principal_name by default, but the SDK doesn't. Any help here is appreciated.


Solution

  • You need to use the azure-graphrbac package: https://pypi.org/project/azure-graphrbac/

    Example of usage:

        objects = graphrbac_client.objects.get_objects_by_object_ids({
            'object_ids': [app.object_id],
            'types': ['ServicePrincipal']
        })
    

    There is a filter syntax as well. I don't have the one that filter with ID, but that gives you an idea:

        users = graphrbac_client.users.list(
            filter="displayName eq 'Test Buddy'"
        )
    

    The doc of graphrbac: https://azuresdkdocs.blob.core.windows.net/$web/python/azure-graphrbac/0.61.1/azure.graphrbac.html

    Some extensive unittests that could help: https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/graphrbac/azure-graphrbac/tests/test_graphrbac.py

    The RestAPI doc could give you some insights into what the SDK can do: https://learn.microsoft.com/en-us/previous-versions/azure/ad/graph/api/api-catalog

    (I work at MS in the Python SDK team)