> ## Documentation Index
> Fetch the complete documentation index at: https://cloudanix.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Azure inactive users remediation

### Triage and Remediation

<Tabs>
  <Tab title="Remediation">
    ### Remediation

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        To remediate inactive users in Azure Active Directory (Azure AD) using the Azure console, follow these steps:

        1. Sign in to the Azure portal (portal.azure.com) using your Azure AD administrator account.

        2. In the left-hand menu, click on "Azure Active Directory" to open the Azure AD dashboard.

        3. In the Azure AD dashboard, click on "Users" to view the list of users in your directory.

        4. Sort the users by the "Last sign-in" column to identify the inactive users. Users with no sign-in activity will have a blank or old date in this column.

        5. Select the inactive users you want to remediate by clicking on their names or using the checkboxes beside their names.

        6. Once the users are selected, click on the "Delete" button at the top of the user list.

        7. In the confirmation dialog, review the selected users and click on "Delete" to remove them from Azure AD.

        8. After the users are deleted, you may want to review any associated resources or permissions they had and update or remove them accordingly.

        9. Additionally, consider enabling Azure AD Premium's "Azure AD Identity Protection" feature to proactively detect and remediate risky sign-in activities.

        By following these steps, you can remediate inactive users in Azure AD using the Azure console.

        #
      </Accordion>

      <Accordion title="Using CLI">
        To remediate inactive users in Azure Active Directory (Azure AD) using Azure CLI, follow these steps:

        1. Install Azure CLI: If you haven't already, install the Azure CLI on your local machine by following the instructions provided by Microsoft.

        2. Sign in to Azure: Open a terminal or command prompt and sign in to your Azure account by running the following command:
           ```
           az login
           ```

        3. Select the Azure subscription: If you have multiple Azure subscriptions, use the following command to select the appropriate subscription:
           ```
           az account set --subscription <subscription_id>
           ```

        4. List inactive users: Use the following command to list all inactive users in Azure AD:
           ```
           az ad user list --query "[?lastSignInDateTime=='null' && userType=='Member'].{displayName:displayName, objectId:objectId}"
           ```

        5. Review the list: Examine the output of the previous command to identify the inactive users that need to be remediated. Note down the `objectId` of each inactive user.

        6. Disable inactive users: For each inactive user identified in the previous step, run the following command to disable the user:

           ```
           az ad user update --id <objectId> --accountEnabled false
           ```

           Replace `<objectId>` with the actual `objectId` of the inactive user.

        7. Verify the changes: To ensure that the users have been disabled, you can use the `az ad user show` command to check the accountEnabled status of each user:

           ```
           az ad user show --id <objectId> --query accountEnabled
           ```

           Replace `<objectId>` with the actual `objectId` of the user.

        8. Repeat step 6 and 7 for each inactive user identified in step 5.

        By following these steps, you can remediate inactive users in Azure AD using Azure CLI.
      </Accordion>

      <Accordion title="Using Python">
        To remediate inactive users in Azure Active Directory (Azure AD) using Python, follow these steps:

        1. Install the required libraries:
           * Install the Azure Identity library: `pip install azure-identity`
           * Install the Azure Management IAM library: `pip install azure-mgmt-authorization`

        2. Import the necessary modules in your Python script:

        ```python theme={null}
        from azure.identity import DefaultAzureCredential
        from azure.mgmt.authorization import AuthorizationManagementClient
        from datetime import datetime, timedelta
        ```

        3. Authenticate with Azure using the DefaultAzureCredential:

        ```python theme={null}
        credential = DefaultAzureCredential()
        subscription_id = "<your-subscription-id>"
        client = AuthorizationManagementClient(credential, subscription_id)
        ```

        4. Define a function to get the list of inactive users:

        ```python theme={null}
        def get_inactive_users(days):
            end_date = datetime.now()
            start_date = end_date - timedelta(days=days)
            filter_str = f"signInActivity/lastSignInDateTime le {end_date.isoformat()} and signInActivity/lastSignInDateTime ge {start_date.isoformat()}"
            
            users = client.users.list(filter=filter_str)
            return users
        ```

        5. Define a function to disable the inactive users:

        ```python theme={null}
        def disable_inactive_users(days):
            users = get_inactive_users(days)
            
            for user in users:
                user.is_account_enabled = False
                client.users.update(user.object_id, user)
        ```

        6. Specify the number of days of inactivity after which a user should be considered inactive:

        ```python theme={null}
        inactive_days_threshold = 90
        ```

        7. Call the `disable_inactive_users` function with the specified number of inactive days:

        ```python theme={null}
        disable_inactive_users(inactive_days_threshold)
        ```

        Make sure you have the necessary permissions to manage users in Azure AD. Adjust the code as necessary to suit your specific requirements and environment.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        # Disable an inactive Azure AD user and remove its Azure IAM role assignments.

        # Provider blocks (add authentication as appropriate for your environment)
        provider "azuread" {
          # Configure auth / tenant here
        }

        provider "azurerm" {
          features {}
        }

        # Azure AD user (principal) – mark as disabled instead of deleting
        resource "azuread_user" "inactive_user" {
          user_principal_name = "INACTIVE_USER_UPN@YOURDOMAIN.TLD"  # substitute with the UPN of the inactive user
          display_name        = "INACTIVE_USER_DISPLAY_NAME"        # substitute with the display name
          mail_nickname       = "INACTIVE_USER_MAIL_NICKNAME"       # substitute with a mail nickname

          # This is the key change: disable the account
          account_enabled = false
        }

        # Example: remove role assignments that grant this user access
        # Delete (or comment out) the azurerm_role_assignment resources that target the inactive user.
        # Below is how such a role assignment would look; it should be REMOVED for an inactive principal.

        # resource "azurerm_role_assignment" "inactive_user_owner_rg" {
        #   scope                = azurerm_resource_group.example.id
        #   role_definition_name = "Owner"
        #   principal_id         = azuread_user.inactive_user.object_id
        # }

        # If you need to keep the block but ensure no assignment exists, you can zero it out:
        # resource "azurerm_role_assignment" "inactive_user_owner_rg" {
        #   count                = 0
        #   scope                = azurerm_resource_group.example.id
        #   role_definition_name = "Owner"
        #   principal_id         = azuread_user.inactive_user.object_id
        # }

        # NOTE: Terraform cannot evaluate "no recent sign-in" itself.
        # You must decide which principals are inactive based on your chosen threshold
        # (for example, from Azure AD sign-in logs) and then point those principals
        # at azuread_user / azuread_service_principal resources with account_enabled = false,
        # and remove all azurerm_role_assignment resources that reference them.
        ```

        This change does not force replacement of the user; it updates `account_enabled` in-place. Removing `azurerm_role_assignment` resources will destroy those assignments, immediately revoking the user’s access to the associated scopes.

        Verification: `terraform plan` should show an in-place update on `azuread_user.inactive_user` changing `account_enabled` from `true` to `false`, and `destroy` actions (or `-` changes) for each `azurerm_role_assignment` you removed or set `count = 0` on.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>
