Share via

Replicate Azure resource access from one user to another existing user.

Ranjith Velamala 110 Reputation points
2025-03-26T08:33:37.84+00:00

Replicate Azure resource access from one user to another existing user.

I can see replicate access to new user but not existing user

Microsoft Security | Microsoft Entra | Microsoft Entra ID

Answer accepted by question author
  1. SrideviM 5,865 Reputation points Volunteer Moderator
    2025-04-07T07:15:41.81+00:00

    Hello Ranjith Velamala,

    I understand you're looking to replicate Azure role assignments from one user to another across different scopes and tenants. This can be challenging, especially with many subscriptions to manage.

    In my setup, I have a user with "Owner" access across all subscriptions within a single tenant. I'm using DefaultAzureCredential for authentication, which picks up my signed-in credentials from the CLI or Visual Studio Code.

    With this, I’m able to loop through all subscriptions, retrieve the source user’s role assignments including those at the subscription, resource group, and resource levels, and replicate them to a target user. The script also checks for existing assignments and avoids duplicates.

    import uuid
    import json
    from azure.identity import DefaultAzureCredential
    from azure.mgmt.resource import SubscriptionClient
    from azure.mgmt.authorization import AuthorizationManagementClient
    from azure.mgmt.authorization.models import RoleAssignmentCreateParameters
    
    # Authenticate using DefaultAzureCredential
    credential = DefaultAzureCredential()
    
    # Initialize Subscription Client
    subscription_client = SubscriptionClient(credential)
    
    # Get all subscriptions
    subscriptions = subscription_client.subscriptions.list()
    
    # Input: Source and Target User Object IDs
    source_user_id = input("Enter the source user's Object ID: ").strip()
    target_user_id = input("Enter the target user's Object ID: ").strip()
    
    # Function to get role assignments for a user in a subscription
    def get_user_roles(subscription_id, user_object_id):
        auth_client = AuthorizationManagementClient(credential, subscription_id)
        scope = f"/subscriptions/{subscription_id}"
        role_assignments = auth_client.role_assignments.list_for_scope(scope)
        user_roles = []
    
        for assignment in role_assignments:
            if assignment.principal_id == user_object_id:
                role_definition_id = assignment.role_definition_id.split("/")[-1]
                try:
                    role = auth_client.role_definitions.get(scope, role_definition_id)
                    user_roles.append({
                        "role_name": role.role_name,
                        "scope": assignment.scope,
                        "role_definition_id": role_definition_id
                    })
                except Exception as e:
                    print(f"Could not retrieve role definition for ID {role_definition_id}: {e}")
    
        return user_roles
    
    # Process each subscription and replicate roles
    for sub in subscriptions:
        sub_id = sub.subscription_id
        print(f"\nProcessing Subscription: {sub_id}")
    
        source_roles = get_user_roles(sub_id, source_user_id)
        if not source_roles:
            print(f"No roles found for user {source_user_id} in subscription {sub_id}")
            continue
    
        print("\nUser access details:")
        print(json.dumps(source_roles, indent=4))
    
        confirm = input("\nDo you want to replicate these roles to the target user in this subscription? (yes/no): ").strip().lower()
        if confirm != "yes":
            print(f"Skipping replication for subscription {sub_id}")
            continue
    
        auth_client = AuthorizationManagementClient(credential, sub_id)
    
        # Get existing roles for target user to avoid duplicates
        target_roles = get_user_roles(sub_id, target_user_id)
        existing_assignments = {
            (role["scope"], role["role_definition_id"]) for role in target_roles
        }
    
        for role in source_roles:
            role_key = (role["scope"], role["role_definition_id"])
            if role_key in existing_assignments:
                print(f"Skipping existing role '{role['role_name']}' at scope {role['scope']}")
                continue
    
            try:
                print(f"Assigning role '{role['role_name']}' to target user at scope: {role['scope']}")
                role_assignment_id = str(uuid.uuid4())
                role_definition_path = f"/subscriptions/{sub_id}/providers/Microsoft.Authorization/roleDefinitions/{role['role_definition_id']}"
    
                auth_client.role_assignments.create(
                    scope=role["scope"],
                    role_assignment_name=role_assignment_id,
                    parameters=RoleAssignmentCreateParameters(
                        role_definition_id=role_definition_path,
                        principal_id=target_user_id
                    )
                )
            except Exception as e:
                print(f"Failed to assign role '{role['role_name']}' at scope {role['scope']}: {e}")
    
        print(f"Role replication completed for subscription {sub_id}")
    
    print("\nAll subscriptions processed.")
    

    Response:

    enter image description here

    This approach works well within a single tenant when the signed-in identity has access to all subscriptions.

    For multi-tenant scenarios, you need to authenticate into each tenant separately using a service principal. This involves creating an app registration in each tenant, assigning it permissions such as Reader and User Access Administrator on the necessary subscriptions, and using ClientSecretCredential with the correct tenant-specific credentials.

    Once authenticated, you can follow the same logic to retrieve role assignments and replicate them. If the source user is a guest in any tenant, their object ID may be different from the one in the home tenant. In that case, you'll need to map or look up the correct object ID within each tenant to ensure accurate results.

    Hope this helps!


    If this answer was helpful, please click "Accept the answer" and mark Yes, as this can help other community members.

    User's image

    If you have any other questions or are still experiencing issues, feel free to ask in the "comments" section, and I'd be happy to help.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.