azureazure-rbacazure-python-sdk

How to assign Reader role to user in Azure Subscription using Python SDK?


I’m trying to assign "Reader" role to user under Azure subscription using Azure Python SDK. I’ve found a way to do it using Azure REST API following MS documentation https://learn.microsoft.com/en-us/azure/role-based-access-control/role-assignments-rest , but I’m not sure how to do the same thing with the SDK.

Here’s the code I’m using with Python’s requests library to call REST API directly:

import requests
import uuid

scope = "subscriptions/{subscription_id}/resourceGroups/{resource_group_name}"
role_assignment_id = str(uuid.uuid4())
role_definition_id = "/providers/Microsoft.Authorization/roleDefinitions/acdd72a7-3385-48ef-bd42-f606fba81ae7"  # Reader role ID
principal_id = "{user_principal_id}"

url = f"https://management.azure.com/{scope}/providers/Microsoft.Authorization/roleAssignments/{role_assignment_id}?api-version=2022-04-01"

access_token = "{access_token}"

headers = {
    "Authorization": f"Bearer {access_token}",
    "Content-Type": "application/json"
}

body = {
    "properties": {
        "roleDefinitionId": role_definition_id,
        "principalId": principal_id
    }
}

response = requests.put(url, headers=headers, json=body)

if response.status_code == 201:
    print("Role assigned successfully.")
else:
    print(f"Failed to assign role. Status Code: {response.status_code}, Response: {response.text}")

The code above works fine, but I want to switch to using Azure Python SDK instead of directly calling the REST API. I’ve searched through the SDK documentation, but I can’t find any example or method that shows how to assign roles like this.


Solution

  • I have one app registration having Owner access under subscription like this:

    enter image description here

    To assign "Reader" role to user under Azure subscription using Azure Python SDK with service principal authentication, make use of below sample code:

    from azure.identity import ClientSecretCredential
    from azure.mgmt.authorization import AuthorizationManagementClient
    import uuid
    
    tenant_id = "tenantId"
    client_id = "appId"
    client_secret = "secret"
    
    subscription_id = "subId"
    scope = "subscriptions/subId"
    role_definition_id = "/providers/Microsoft.Authorization/roleDefinitions/acdd72a7-3385-48ef-bd42-f606fba81ae7"
    principal_id = "userId"
    
    role_assignment_id = str(uuid.uuid4())
    
    credential = ClientSecretCredential(
        tenant_id=tenant_id,
        client_id=client_id,
        client_secret=client_secret
    )
    
    authorization_client = AuthorizationManagementClient(credential, subscription_id)
    
    try:
        role_assignment = authorization_client.role_assignments.create(
            scope=scope,
            role_assignment_name=role_assignment_id,
            parameters={
                "properties": {
                    "roleDefinitionId": role_definition_id,
                    "principalId": principal_id
                }
            }
        )
        print("Role assigned successfully:", role_assignment)
    except Exception as e:
        print("Failed to assign role:", str(e))
    

    Response:

    enter image description here

    To confirm that, I checked the same in Portal where Reader role assigned successfully to user under subscription as below:

    enter image description here