0

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.

12
  • Could you confirm whether your requirement is to assign Reader role to user using Azure Python SDK under subscription scope? Commented Dec 11, 2024 at 11:20
  • Yes @Sridevi that's exactly what I need. Please help Commented Dec 11, 2024 at 11:47
  • Could you confirm whether you want to authenticate using service principal or signed-in user? Commented Dec 11, 2024 at 11:51
  • obtained bearer token with app owner access, but the user sign-ins aren't applicable to our situation. Is that what you refer to as authentication? Commented Dec 11, 2024 at 12:13
  • 1
    It worked like a charm! Thanks a ton, Sridevi! Commented Dec 11, 2024 at 13:37

3 Answers 3

0

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

Sign up to request clarification or add additional context in comments.

Comments

0

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))

2 Comments

DefaultAzureCredential failed to retrieve a token from the included credentials. Attempted credentials:EnvironmentCredential: EnvironmentCredential authentication unavailable. Environment variables are not fully configured.Visit aka.ms/azsdk/python/identity/environmentcredential/troubleshoot to troubleshoot this issue. ManagedIdentityCredential: ManagedIdentityCredential authentication unavailable.SharedTokenCacheCredential: SharedTokenCacheCredential authentication unavailable. No accounts were found in the cache.AzureCliCredential: Please run 'az login' to set up an account
Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. Would you kindly edit your answer to include additional details for the benefit of the community?
0

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.

1 Comment

No worries, code from Sridevi is working well at the moment!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.