agent: |
jIjIzaTdFg92afoWFga8Assign Group Memberships to Azure AD User
Assign Group Memberships to Azure AD User
There was a problem that the LLM was not able to address. Please rephrase your prompt and try again.
Assign a user to specific Azure AD group memberships to grant access to necessary resources and define permissions based on organizational roles.
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 the Azure credentials
credential = ClientSecretCredential(tenant_id, client_id, client_secret)
def get_user_details(user_id):
"""Fetch user details by user ID."""
url = f"https://graph.microsoft.com/v1.0/users/{user_id}"
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()
return response.json()
except requests.exceptions.HTTPError as e:
print(f"Failed to retrieve user details: {e.response.status_code} - {e.response.text}")
return None
def get_group_id_by_name(group_name):
"""Retrieve the object ID of a group by its display name."""
url = f"https://graph.microsoft.com/v1.0/groups?$filter=displayName eq '{group_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()
groups = response.json().get('value')
if groups:
group_id = groups[0]['id']
print(f"Group '{group_name}' found with ID: {group_id}")
return group_id
else:
print(f"No group found with the name: {group_name}")
return None
except requests.exceptions.HTTPError as e:
print(f"Failed to retrieve group: {e.response.status_code} - {e.response.text}")
return None
def add_user_to_group(user_id, group_id, group_name):
"""Add a user to a group using the user and group object IDs."""
user_details = get_user_details(user_id)
if user_details:
url = f"https://graph.microsoft.com/v1.0/groups/{group_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 '{user_details['displayName']}' with ID: {user_id} was successfully added to group '{group_name}' (ID: {group_id}).")
except requests.exceptions.HTTPError as e:
print(f"Failed to add user to group: {e.response.status_code} - {e.response.text}")
# Example usage:
# group_name = "m365_test_group" # Specify the display name of the group
# user_id = "7f16743b-2b12-4697-b065-d9637a1b30e7" # Specify the object ID of the user
# user_info to be received from upstream task
user_id = user_info["id"]
# Get the group ID by name
group_id = get_group_id_by_name(group_name)
if group_id:
# Add the user to the group if the group was found
add_user_to_group(user_id, group_id, group_name)
"""
# Sample Output
Group 'm365_test_group' found with ID: 80fc1ee5-90b5-4d89-81ab-718f5a74d202
User 'John Doe' with ID: 7f16743b-2b12-4697-b065-d9637a1b30e7 was successfully added to group 'm365_test_group' (ID: 80fc1ee5-90b5-4d89-81ab-718f5a74d202).
"""
copied