> ## 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.

# Monitor the Total Number of Subscription Owners

### More Info:

Ensure that the total number of subscription owners within your Azure account is monitored.

### Risk Level

Medium

### Address

Operational Maturity, Security

### Compliance Standards

* Cloudanix Best Practice

### Triage and Remediation

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

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        Sure! Here are the step-by-step instructions to remediate the misconfiguration of monitoring the total number of subscription owners in Azure:

        1. Open the Azure portal and log in with your credentials.
        2. Navigate to the Azure Active Directory service.
        3. Click on the "Enterprise applications" option from the left-hand side menu.
        4. In the search bar, type "Azure AD Privileged Identity Management" and select it from the search results.
        5. Click on the "Manage" button to open the Azure AD Privileged Identity Management console.
        6. From the left-hand side menu, select "Roles and administrators".
        7. In the "Roles and administrators" page, select "Add" to add a new role assignment.
        8. In the "Add assignment" page, select "Owner" from the "Directory roles" dropdown list.
        9. In the "Select" page, select the user or group that you want to assign the "Owner" role to.
        10. Click on the "Assign" button to complete the role assignment.
        11. Repeat steps 7-10 for all the users or groups that need to be assigned the "Owner" role.
        12. Once all the users or groups are assigned the "Owner" role, go back to the Azure AD Privileged Identity Management console and select "Settings" from the left-hand side menu.
        13. In the "Settings" page, select "Notifications".
        14. In the "Notifications" page, select "Add notification".
        15. In the "Add notification" page, configure the notification settings as per your requirements.
        16. Click on the "Save" button to save the notification settings.

        By following these steps, you will be able to remediate the misconfiguration of monitoring the total number of subscription owners in Azure using the Azure console.

        #
      </Accordion>

      <Accordion title="Using CLI">
        The misconfiguration "Monitor the Total Number of Subscription Owners" can be remediated in Azure using the following steps:

        1. Open a command prompt or terminal window.

        2. Login to Azure using the Azure CLI command:

           ```
           az login
           ```

        3. Select the subscription that you want to monitor using the following command:

           ```
           az account set --subscription <subscription-id>
           ```

        4. Retrieve the number of subscription owners using the following command:

           ```
           az role assignment list --role Owner --query "[].principalName" --output tsv | sort | uniq | wc -l
           ```

           This command retrieves all the role assignments with the "Owner" role, filters out the principal names, sorts and counts the unique principal names.

        5. Set up a notification to alert you when the number of subscription owners changes. You can use Azure Monitor to create an alert rule that sends an email or SMS notification when the number of subscription owners exceeds a certain threshold.

           ```
           az monitor metrics alert create -n "<alert-name>" --description "<alert-description>" --condition "total subscription owners > <threshold>" --resource-type "Microsoft.Subscription" --resource "<subscription-id>" --window-size 5m --evaluation-frequency 1m --severity 3 --action email <email-address>
           ```

           Replace `<alert-name>` and `<alert-description>` with a name and description for your alert, `<threshold>` with the number of subscription owners that triggers the alert, `<subscription-id>` with the ID of your subscription, and `<email-address>` with the email address to which notifications should be sent.

           This command creates an alert rule that monitors the "total subscription owners" metric for your subscription, evaluates it every minute, and sends an email notification if the threshold is exceeded.

        6. Verify that the alert is working by adding or removing subscription owners and checking that you receive notifications when the threshold is exceeded.

        By following these steps, you can remediate the misconfiguration "Monitor the Total Number of Subscription Owners" in Azure using Azure CLI.
      </Accordion>

      <Accordion title="Using Python">
        To monitor the total number of subscription owners in Azure, you can use the Azure Management API. Here are the steps to remediate this issue using Python:

        Step 1: Install the Azure SDK for Python

        You can install the Azure SDK for Python using pip. Open the terminal and run the following command:

        ```python theme={null}
        pip install azure-mgmt-resource
        ```

        Step 2: Authenticate with Azure

        To authenticate with Azure, you need to create a service principal. You can create a service principal using the Azure CLI or the Azure portal. Once you have the service principal details, you can use them to authenticate with Azure. Here's an example code snippet:

        ```python theme={null}
        from azure.common.credentials import ServicePrincipalCredentials

        TENANT_ID = '<your tenant id>'
        CLIENT_ID = '<your client id>'
        CLIENT_SECRET = '<your client secret>'

        credentials = ServicePrincipalCredentials(
            client_id=CLIENT_ID,
            secret=CLIENT_SECRET,
            tenant=TENANT_ID
        )
        ```

        Step 3: Get the Subscription Owners

        Once you're authenticated with Azure, you can use the Azure Management API to get the subscription owners. Here's an example code snippet:

        ```python theme={null}
        from azure.mgmt.resource import ResourceManagementClient

        subscription_id = '<your subscription id>'

        resource_client = ResourceManagementClient(credentials, subscription_id)

        owners = resource_client.providers.get('Microsoft.Authorization').get('resourceGroups', 'providers/Microsoft.Authorization/roleAssignments').properties.permissions[0].actions[0].notActions[0].dataActions[0].notDataActions[0].principalIds

        total_owners = len(owners)
        ```

        This code snippet gets the subscription owners by querying the Azure Management API. The `ResourceManagementClient` is used to interact with the Azure Resource Manager API. The `providers.get` method is used to get the role assignments for the Microsoft.Authorization provider. The `properties.permissions` attribute contains the list of permissions for the provider. The `actions` attribute contains the list of actions that can be performed on the resource. The `notActions` attribute contains the list of actions that cannot be performed on the resource. The `dataActions` attribute contains the list of data actions that can be performed on the resource. The `notDataActions` attribute contains the list of data actions that cannot be performed on the resource. Finally, the `principalIds` attribute contains the list of principal IDs for the role assignment.

        Step 4: Remediate the Issue

        To remediate the issue, you need to ensure that there are no more than two subscription owners. If there are more than two subscription owners, you can remove the excess owners. Here's an example code snippet:

        ```python theme={null}
        if total_owners > 2:
            excess_owners = total_owners - 2
            print(f'Total number of subscription owners: {total_owners}. Excess owners: {excess_owners}.')
            # Code to remove excess owners
        else:
            print(f'Total number of subscription owners: {total_owners}.')
        ```

        This code snippet checks if there are more than two subscription owners. If there are, it calculates the number of excess owners and prints a message indicating the total number of subscription owners and the number of excess owners. You can replace the comment with the code to remove the excess owners.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        data "azurerm_subscription" "current" {}

        resource "azurerm_policy_assignment" "monitor_subscription_owners" {
          name                 = "monitor-subscription-owners"
          display_name         = "Monitor total number of subscription owners"
          scope                = data.azurerm_subscription.current.id
          policy_definition_id = "POLICY_DEFINITION_ID_FOR_MONITOR_SUBSCRIPTION_OWNERS"

          # Replace POLICY_PARAMETER_NAME with the exact parameter name from the built-in policy
          # (for example, something like "maximumOwners" or "allowedOwnerCount"),
          # and OWNER_THRESHOLD with the integer limit you require.
          parameters = jsonencode({
            POLICY_PARAMETER_NAME = {
              value = OWNER_THRESHOLD
            }
          })
        }
        ```

        Substitute:

        * `POLICY_DEFINITION_ID_FOR_MONITOR_SUBSCRIPTION_OWNERS` with the full resource ID of the built‑in Azure Policy used by Security Center to monitor subscription owners (from Azure Portal or `az policy definition list`).
        * `POLICY_PARAMETER_NAME` with the exact parameter name that represents the owner-count threshold for that policy.
        * `OWNER_THRESHOLD` with your numeric limit (for example `5`).

        This change creates or updates only the `azurerm_policy_assignment` and does not force replacement of the subscription or other resources.

        For verification, `terraform plan` should show:

        * `+ azurerm_policy_assignment.monitor_subscription_owners` being created (or updated if you are correcting an existing, misconfigured assignment) with the specified `policy_definition_id` and `parameters`.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>
