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
Try this:
I have one app registration having
Owner
access under subscription like this:To assign "Reader" role to user under Azure subscription using Azure Python SDK with service principal authentication, make use of below sample code:
Response:
To confirm that, I checked the same in Portal where Reader role assigned successfully to user under subscription as below:
Set the following environment variables with appropriate values for your Azure service principal:
After setting these variables, DefaultAzureCredential will use them to authenticate.