agent: |
Disable/Delete Inactive Users in Microsoft Entra ID(Azure AD)
This runbook identifies users in Azure Active Directory who have not signed in for a specified duration. These users are then either disabled or deleted from the directory. This process enhances security and optimizes resource usage by ensuring that only active users have access to organizational resources and applications which helps in maintaining an efficient and secure user base in Microsoft Entra ID(Azure AD).
- 1nQgDM95JkpjjQ71IRHWpGet Azure Subscription Id from CLI
1
Get Azure Subscription Id from CLI
There was a problem that the LLM was not able to address. Please rephrase your prompt and try again.This task retrieves the unique identifier for an Azure subscription using the Azure CLI. This ID is essential for managing resources and services tied to a specific Azure subscription programmatically.
inputsoutputsimport json try: result = _exe(None, "az account show") account_info = json.loads(result) subscription_id = account_info["id"] print("Fetched Subscription Id") print(subscription_id) # for debugging except json.JSONDecodeError: print("Error decoding JSON response from Azure CLI.") subscription_id = Nonecopied1 - 2KXHnOn2qiFEdHtCRwY4AList All Users in Microsoft Entra ID(Azure AD)
2
List All Users in Microsoft Entra ID(Azure AD)
There was a problem that the LLM was not able to address. Please rephrase your prompt and try again.This task retrieves all user accounts within an Azure Active Directory tenant. It's essential for administrative tasks such as compliance, user management, and reporting, offering a comprehensive view of the user identities in an organization.
inputsoutputsfrom azure.identity import DefaultAzureCredential, CredentialUnavailableError from msgraph.core import GraphClient import requests # Define the scopes scopes = ['https://graph.microsoft.com/.default'] try: # Initialize the DefaultAzureCredential to handle the authentication credential = DefaultAzureCredential() # Instantiate the GraphClient with the credential and the specified scopes client = GraphClient(credential=credential, scopes=scopes) # Send a GET request to list all users users_response = client.get('/users') users_response.raise_for_status() # Raise an exception for HTTP error responses # Parse the response to JSON users = users_response.json() # Check if the response contains users if not users.get('value', []): print("No users found in Azure Active Directory.") else: # Header for the table header = f"{'Display Name':<30} | {'User Principal Name':<55} | {'ID':<36}" print(header) print("-" * len(header)) for user in users['value']: display_name = user.get('displayName', 'N/A') user_principal_name = user.get('userPrincipalName', 'N/A') user_id = user.get('id', 'N/A') user_row = f"{display_name:<30} | {user_principal_name:<55} | {user_id:<36}" print(user_row) print("-" * len(header)) except CredentialUnavailableError as e: print("Credential error occurred while authenticating to Azure AD:", e) except requests.exceptions.HTTPError as e: print("HTTP error occurred while making a request to the Graph API:", e) except Exception as e: print("An unexpected error occurred:", e)copied2 - 3kXsoBdKXb4OCu0gI5JauFilter Out Inactive Users in Microsoft Entra ID (Azure AD)
3
Filter Out Inactive Users in Microsoft Entra ID (Azure AD)
There was a problem that the LLM was not able to address. Please rephrase your prompt and try again.This task identifies users in Azure Active Directory who haven't been active for a specified period. This aids in enhancing security and managing user accounts efficiently, enabling actions like account review or deactivation for better organizational control and security compliance.
inputsoutputsfrom azure.identity import DefaultAzureCredential from msgraph.core import GraphClient from datetime import datetime, timedelta # Define the scopes scopes = ['https://graph.microsoft.com/.default'] # Initialize the DefaultAzureCredential to handle the authentication credential = DefaultAzureCredential() # Instantiate the GraphClient with the credential and the specified scopes client = GraphClient(credential=credential, scopes=scopes) # Define the threshold for inactivity (in days) inactive_days_threshold =30 # Calculate the cutoff date for inactivity (timezone-naive for comparison) cutoff_date = datetime.utcnow() - timedelta(days=inactive_days_threshold) users_data = users # Check if users data is available if not users_data.get('value'): print("No users found in Azure Active Directory.") else: inactive_users = [] for user in users_data['value']: display_name = user.get('displayName', 'N/A') upn = user.get('userPrincipalName', 'N/A') sign_in_activity = user.get('signInActivity', {}) last_sign_in = sign_in_activity.get('lastSignInDateTime') if last_sign_in: last_sign_in_date = datetime.fromisoformat(last_sign_in.replace('Z', '+00:00')).replace(tzinfo=None) if last_sign_in_date < cutoff_date: inactive_users.append(user) else: inactive_users.append(user) print(f"Found {len(inactive_users)} inactive users based on the {inactive_days_threshold}-day threshold.") for user in inactive_users: display_name = user.get('displayName', 'N/A') upn = user.get('userPrincipalName', 'N/A') last_sign_in = user.get('signInActivity', {}).get('lastSignInDateTime', 'No sign-in activity recorded') print(f"User: {display_name} ({upn})") print(f" Last Sign-In: {last_sign_in}") print("-" * 30) #print(users_data) # for debugging #print(inactive_users) # for debuggingcopied3 - 4ZdAzd3zM24VClAMTrF1BDisable Users in Microsoft Entra ID (Azure AD)
4
Disable Users in Microsoft Entra ID (Azure AD)
There was a problem that the LLM was not able to address. Please rephrase your prompt and try again.This task deactivates user accounts in Azure Active Directory to prevent access to organizational resources. Disabling accounts helps maintain security and manage user privileges effectively within an organization's IT infrastructure.
inputsoutputsfrom azure.identity import DefaultAzureCredential from msgraph.core import GraphClient # Sample inactive users list inactive_users = [{'displayName': 'test-user', 'userPrincipalName': 'test-user@yashyadav34gmail.onmicrosoft.com', 'id': '71f44091-8d06-4a8b-8d36-5ff79d753675'}] # Initialize the DefaultAzureCredential and GraphClient credential = DefaultAzureCredential() client = GraphClient(credential=credential, scopes=['https://graph.microsoft.com/.default']) def disable_user(user_id): try: response = client.patch(f'/users/{user_id}', json={'accountEnabled': False}) if response.status_code == 204: return True else: return False except Exception as e: print(f"An unexpected error occurred while disabling user {user_id}: {e}") return False # Initialize the list for disabled users disabled_users = [] # Check if there are any inactive users to process if not inactive_users: print("No inactive users provided for processing.") else: disabled_count = 0 for user in inactive_users: display_name = user.get('displayName', 'N/A') upn = user.get('userPrincipalName', 'N/A') user_id = user.get('id') print(f"Processing user: {display_name} ({upn})") # Disable the user account if disable_user(user_id): print(f"Successfully disabled user: {display_name} ({upn})") disabled_users.append(user) # Add the user to the disabled_users list disabled_count += 1 else: print(f"Failed to disable user: {display_name} ({upn})") print("-" * 30) print(f"Operation completed. {disabled_count} out of {len(inactive_users)} inactive users were disabled.") #print(f"Disabled Users: {disabled_users}") # for debuggingcopied4 - 5y4WjjKrw5sIaPIG4GKBTDelete Users in Microsoft Entra ID (Azure AD)
5
Delete Users in Microsoft Entra ID (Azure AD)
There was a problem that the LLM was not able to address. Please rephrase your prompt and try again.This task permanently removes user accounts from Azure Active Directory. This is crucial for ensuring former employees or associates no longer have access to organizational resources. It helps maintain security by preventing unauthorized access to services and applications linked to Azure AD.
inputsoutputsfrom azure.identity import DefaultAzureCredential from msgraph.core import GraphClient # Initialize the DefaultAzureCredential and GraphClient credential = DefaultAzureCredential() client = GraphClient(credential=credential, scopes=['https://graph.microsoft.com/.default']) ''' inactive_users = { '@odata.context': 'https://graph.microsoft.com/v1.0/$metadata#users(displayName,userPrincipalName,signInActivity)', 'value': [ {'displayName': 'test-user', 'userPrincipalName': 'test-user@yashyadav34gmail.onmicrosoft.com', 'id': '9b8d2682-d8c8-41ac-b2dd-3bc0552b4cc9'} ] } ''' def delete_user(user_id): try: response = client.delete(f'/users/{user_id}') return response.status_code == 204 except Exception as e: print(f"An unexpected error occurred while deleting user {user_id}: {e}") return False # Check if there are any inactive users to process if not inactive_users.get('value'): print("No inactive users provided for processing.") else: deletion_count = 0 total_users = len(inactive_users['value']) for user in inactive_users['value']: user_id = user.get('id') display_name = user.get('displayName', 'N/A') upn = user.get('userPrincipalName', 'N/A') print(f"Processing deletion for user: {display_name} ({upn})") # Delete the user account if delete_user(user_id): print(f"Successfully deleted user: {display_name} ({upn})") deletion_count += 1 else: print(f"Failed to delete user: {display_name} ({upn})") print("-" * 30) print(f"Operation completed. {deletion_count} out of {total_users} inactive users were deleted.")copied5