skip to Main Content

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.

3

Answers


  1. Try this:

    from azure.identity import DefaultAzureCredential
    
    from azure.mgmt.authorization import AuthorizationManagementClient
    
    import uuid
    
    subscription_id = "{subscription_id}"
    
    resource_group_name = "{resource_group_name}"
    
    principal_id = "{user_principal_id}"  # User's object ID in Azure AD
    
    role_definition_id = "/subscriptions/{subscription_id}/providers/Microsoft.Authorization/roleDefinitions/acdd72a7-3385-48ef-bd42-f606fba81ae7"  
    
    scope = f"/subscriptions/{subscription_id}/resourceGroups/{resource_group_name}"
    
    role_assignment_id = str(uuid.uuid4())
    
    credential = DefaultAzureCredential()
    
    auth_client = AuthorizationManagementClient(credential, subscription_id)
    
    try:
        role_assignment = auth_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))
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
  3. Set the following environment variables with appropriate values for your Azure service principal:

    set AZURE_CLIENT_ID=your-client-id
    set AZURE_TENANT_ID=your-tenant-id
    set AZURE_CLIENT_SECRET=your-client-secret
    

    After setting these variables, DefaultAzureCredential will use them to authenticate.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search