agent: |
Lh1GuniArFLrcwg2Ts6FAssign Roles to Azure AD User
Assign Roles to Azure AD User
There was a problem that the LLM was not able to address. Please rephrase your prompt and try again.
Allocate predefined Azure AD roles to a user to specify their permissions and access levels within the organization's IT environment.
inputs
outputs
import requests
from azure.identity import ClientSecretCredential
# Set up Azure AD credentials
tenant_id = 'your-tenant-id'
client_id = "your-client-id"
client_secret = "your-client-secret"
# Initialize Azure credentials
credential = ClientSecretCredential(tenant_id, client_id, client_secret)
def get_directory_role_id(role_name):
"""Retrieve the role ID by role name from directory roles."""
url = f"https://graph.microsoft.com/v1.0/directoryRoles?$filter=displayName eq '{role_name}'"
access_token = credential.get_token('https://graph.microsoft.com/.default').token
headers = {'Authorization': f'Bearer {access_token}', 'Content-Type': 'application/json'}
response = requests.get(url, headers=headers)
try:
response.raise_for_status()
roles = response.json().get('value')
if roles:
role_id = roles[0]['id']
print(f"Directory role '{role_name}' found with ID: {role_id}")
return role_id
else:
print(f"No directory role found with the name: {role_name}")
return None
except requests.exceptions.HTTPError as e:
print(f"Failed to retrieve directory role: {e.response.status_code} - {e.response.text}")
return None
def assign_role_to_user(user_id, role_id):
"""Assign a directory role to a user using the role ID and user's object ID."""
url = f"https://graph.microsoft.com/v1.0/directoryRoles/{role_id}/members/$ref"
access_token = credential.get_token('https://graph.microsoft.com/.default').token
headers = {'Authorization': f'Bearer {access_token}', 'Content-Type': 'application/json'}
payload = {"@odata.id": f"https://graph.microsoft.com/v1.0/directoryObjects/{user_id}"}
response = requests.post(url, headers=headers, json=payload)
try:
response.raise_for_status()
print(f"User with ID: {user_id} was successfully assigned to the role with ID: {role_id}.")
except requests.exceptions.HTTPError as e:
print(f"Failed to assign role to user: {e.response.status_code} - {e.response.text}")
# Example usage
# role_name = "Global Reader"
# user_id = "7f16743b-2b12-4697-b065-d9637a1b30e7"
# user_info to be received from upstream task
user_id = user_info["id"]
# Get the directory role ID by name
role_id = get_directory_role_id(role_name)
if role_id:
# Assign the role to the user if the role was found
assign_role_to_user(user_id, role_id)
"""
# Sample Output
Directory role 'Global Reader' found with ID: b3610c45-b84c-40c9-8de2-bec0341b3843
User with ID: 7f16743b-2b12-4697-b065-d9637a1b30e7 was successfully assigned to the role with ID: b3610c45-b84c-40c9-8de2-bec0341b3843.
"""
copied