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

# Setup Alerts for Delete Virtual Machine Events

### More Info:

Ensure that a Microsoft Azure activity log alert is fired whenever a 'Delete Virtual Machine' event is triggered within your cloud account. An Azure activity log alert fires each time the action event that matches the condition specified in the alert configuration is triggered. The alert condition that this rule searches for is `Whenever the Administrative Activity Log 'Delete Virtual Machine (Microsoft.Compute/virtualMachines)' has 'any' level, with 'any' status and event is initiated by 'any'`

### Risk Level

High

### Address

Security

### Compliance Standards

CBP, CIS Microsoft Azure Foundations

### Triage and Remediation

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

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        Below are step‑by‑step instructions to set up alerts for **Delete Virtual Machine** events in Azure using the **Azure Portal (console)**.

        ***

        ## Goal

        Create an **Activity log alert** that fires whenever a **virtual machine is deleted**.

        ***

        ## Step 1 – Open Monitor (Activity Log Alerts)

        1. Sign in to the **Azure Portal**: [https://portal.azure.com](https://portal.azure.com)
        2. In the left-hand menu, select **Monitor**.
        3. In the Monitor blade, click **Alerts**.
        4. Click **+ Create** > **Alert rule**.

        ***

        ## Step 2 – Select the Scope (Subscription / Resource Group)

        1. Under **Scope**, click **Select scope**.
        2. Choose one of:
           * Entire **subscription** (to catch deletes for all VMs), or
           * A specific **resource group** (only VMs in that RG).
        3. Click **Apply**.

        > Note: You generally *cannot* scope an activity log alert directly to a single VM, because delete events appear at subscription/RG level. Use subscription or RG scope.

        ***

        ## Step 3 – Choose the Condition (Delete VM Operation)

        1. Under **Condition**, click **Add condition**.

        2. In the **Signal type** list, select **Activity log** (if not filtered already).

        3. In the list of signals, find and select:
           * **Delete Virtual Machine (Microsoft.Compute/virtualMachines/delete)**\
             (The exact wording may appear as an operation like `Microsoft.Compute/virtualMachines/delete`.)

        4. Once selected, a configuration pane opens.

        5. Optionally refine:
           * **Status** = `Succeeded` (to only alert when a delete actually completes).

        6. Click **Done**.

        ***

        ## Step 4 – Configure the Action Group (How You Get Notified)

        If you already have an action group, you can reuse it; otherwise:

        1. Under **Actions**, click **+ Add action groups**.
        2. Click **+ Create action group**.
        3. Fill in:
           * **Subscription** and **Resource group**.
           * **Action group name** and **Display name**.
        4. Under **Notifications**:
           * Click **+ Add notification**.
           * Choose **Email/SMS/Push/Voice**.
           * Provide **email address** (and/or phone, etc.).
           * Click **OK** / **Add**.
        5. (Optional) Under **Actions**, you can add:
           * **ITSM**, **Webhook**, **Function**, **Logic App**, etc.
        6. Click **Review + create**, then **Create**.
        7. Back in the alert rule, ensure the created **Action group** is selected.
        8. Click **Apply**.

        ***

        ## Step 5 – Set Alert Rule Details

        1. Under **Alert rule details**:
           * **Alert rule name**: e.g. `Alert - VM Deleted`
           * **Description**: e.g. `Alert when any virtual machine delete operation succeeds.`
           * **Resource group**: Choose where to store this alert rule’s metadata.
        2. Set **Severity**:
           * For deletions, choose something like **Sev 2 (Error)** or **Sev 1 (Critical)** depending on your policy.
        3. Ensure **Enable rule upon creation** is **On**.

        ***

        ## Step 6 – Create the Alert Rule

        1. Click **Review + create**.
        2. Validate settings, then click **Create**.

        ***

        ## Step 7 – (Optional) Test the Alert

        1. Delete a test VM in the chosen scope (subscription/RG).
        2. Once the delete completes (Activity log shows success), verify that:
           * The **alert is fired** under **Monitor > Alerts**, and
           * Notification (email/SMS/etc.) is received.

        ***

        This completes remediation: Azure will now generate alerts via the configured action group whenever a **Delete Virtual Machine** event occurs within your defined scope.
      </Accordion>

      <Accordion title="Using CLI">
        Below is a minimal, end-to-end Azure CLI example to set up alerts for “Delete Virtual Machine” events in Azure (Compute). Adjust names/IDs as needed.

        ***

        ### 1. Set basic variables

        ```bash theme={null}
        # IDs & names to customize
        SUBSCRIPTION_ID="<your-subscription-id>"
        RESOURCE_GROUP="<rg-for-alert>"
        LOCATION="eastus"

        ALERT_NAME="vm-delete-alert"
        ACTION_GROUP_NAME="vm-delete-ag"
        ACTION_GROUP_SHORT_NAME="vmDelAG"

        EMAIL_ADDRESS="<your-email@example.com>"
        ```

        (Optional) Set the subscription:

        ```bash theme={null}
        az account set --subscription "$SUBSCRIPTION_ID"
        ```

        ***

        ### 2. Create (or choose) a resource group

        ```bash theme={null}
        az group create \
          --name "$RESOURCE_GROUP" \
          --location "$LOCATION"
        ```

        ***

        ### 3. Create an Action Group (email notification)

        ```bash theme={null}
        az monitor action-group create \
          --name "$ACTION_GROUP_NAME" \
          --resource-group "$RESOURCE_GROUP" \
          --short-name "$ACTION_GROUP_SHORT_NAME" \
          --action email AdminEmail "$EMAIL_ADDRESS"
        ```

        This will be the notification target for the alert.

        ***

        ### 4. Create an Activity Log Alert for VM delete events

        This watches the Activity Log for the “Delete Virtual Machine” operation and fires the action group.

        ```bash theme={null}
        az monitor activity-log alert create \
          --name "$ALERT_NAME" \
          --resource-group "$RESOURCE_GROUP" \
          --scopes "/subscriptions/$SUBSCRIPTION_ID" \
          --condition "category=Administrative and operationName='Microsoft.Compute/virtualMachines/delete' and status=Succeeded" \
          --action-group "$(az monitor action-group show -g $RESOURCE_GROUP -n $ACTION_GROUP_NAME --query id -o tsv)" \
          --description "Alert when any Azure VM is deleted in this subscription"
        ```

        Notes:

        * `category=Administrative` targets control-plane operations.
        * `operationName='Microsoft.Compute/virtualMachines/delete'` is the VM delete event.
        * `status=Succeeded` ensures alert only when deletion actually completes.
        * `--scopes` can be narrowed to a specific resource group if you prefer (e.g. `/subscriptions/$SUBSCRIPTION_ID/resourceGroups/<rg-name>`).

        ***

        ### 5. Verify the alert

        List activity log alerts:

        ```bash theme={null}
        az monitor activity-log alert list --resource-group "$RESOURCE_GROUP" -o table
        ```

        You can test by deleting a test VM and confirming you receive the email from the action group.
      </Accordion>

      <Accordion title="Using Python">
        Below are step‑by‑step remediation instructions and a Python example to create an **Activity Log alert** in Azure Monitor for **VM delete events** (`Microsoft.Compute/virtualMachines/delete`).

        ***

        ## 1. What you will create

        An **Activity Log alert rule** that fires when any VM is deleted in a chosen subscription, and sends a notification (e.g., email / action group).

        ***

        ## 2. Prerequisites

        1. **Azure CLI** (for login / testing)

        2. **Python packages**:
           ```bash theme={null}
           pip install azure-identity azure-mgmt-monitor
           ```

        3. **Permissions**:
           * `Monitoring Contributor` or higher on the subscription (to create alert rule)
           * `Contributor` (or similar) on the resource group where the alert will live

        4. **Authentication**: one of:
           * `az login` for interactive user + `DefaultAzureCredential`
           * Or a Service Principal with `AZURE_CLIENT_ID`, `AZURE_TENANT_ID`, `AZURE_CLIENT_SECRET` in env vars.

        ***

        ## 3. Decide the key parameters

        Collect these values first:

        * `subscription_id` – subscription where the VMs live
        * `resource_group_name` – resource group to store the alert rule
        * `alert_rule_name` – e.g. `"vm-delete-activity-log-alert"`
        * `action_group_id` – Resource ID of an existing Action Group (for email / webhook / etc.), e.g.:

          ```
          /subscriptions/<SUB_ID>/resourceGroups/<RG_NAME>/providers/microsoft.insights/actionGroups/<ACTION_GROUP_NAME>
          ```

        If you do not have an action group, create one in the portal or via CLI first.

        ***

        ## 4. Activity Log Alert Rule Definition

        We want to create a rule with:

        * **Scope**: the subscription\
          `scope = f"/subscriptions/{subscription_id}"`

        * **Condition**:
          * Category: `Administrative`
          * Operation Name: `Microsoft.Compute/virtualMachines/delete`
          * Status: `Succeeded` (so only successful deletes trigger it)

        ***

        ## 5. Python code to create the alert

        ```python theme={null}
        from datetime import datetime
        from azure.identity import DefaultAzureCredential
        from azure.mgmt.monitor import MonitorManagementClient
        from azure.mgmt.monitor.models import (
            ActivityLogAlertResource,
            ActivityLogAlertAllOfCondition,
            ActivityLogAlertLeafCondition,
            ActivityLogAlertActionGroup
        )

        # -----------------------------
        # CONFIGURE THESE VALUES
        # -----------------------------
        subscription_id = "<YOUR_SUBSCRIPTION_ID>"
        resource_group_name = "<RESOURCE_GROUP_NAME_FOR_ALERT>"
        alert_rule_name = "vm-delete-activity-log-alert"

        # Resource ID of an existing Action Group
        action_group_id = (
            "/subscriptions/<SUBSCRIPTION_ID>/resourceGroups/<RG_NAME>"
            "/providers/microsoft.insights/actionGroups/<ACTION_GROUP_NAME>"
        )

        # -----------------------------
        # AUTHENTICATION
        # -----------------------------
        credential = DefaultAzureCredential()
        monitor_client = MonitorManagementClient(credential, subscription_id)

        # -----------------------------
        # BUILD THE ACTIVITY LOG ALERT
        # -----------------------------

        # Scope: monitor all VM delete operations in the subscription
        scopes = [f"/subscriptions/{subscription_id}"]

        # Conditions: Administrative category AND specific operationName
        condition = ActivityLogAlertAllOfCondition(
            all_of=[
                ActivityLogAlertLeafCondition(
                    field="category",
                    equals="Administrative"
                ),
                ActivityLogAlertLeafCondition(
                    field="operationName",
                    equals="Microsoft.Compute/virtualMachines/delete"
                ),
                ActivityLogAlertLeafCondition(
                    field="status",
                    equals="Succeeded"
                )
            ]
        )

        # Action: send to Action Group
        actions = [
            ActivityLogAlertActionGroup(
                action_group_id=action_group_id,
                webhook_properties={
                    # Optional custom properties
                    "source": "vm-delete-activity-log-alert"
                }
            )
        ]

        alert = ActivityLogAlertResource(
            location="global",
            scopes=scopes,
            condition=condition,
            actions={"actionGroups": actions},
            enabled=True,
            description="Alert when any Azure VM is deleted in this subscription."
        )

        # -----------------------------
        # CREATE OR UPDATE ALERT RULE
        # -----------------------------
        result = monitor_client.activity_log_alerts.create_or_update(
            resource_group_name=resource_group_name,
            activity_log_alert_name=alert_rule_name,
            activity_log_alert=alert
        )

        print("Created/updated Activity Log alert:")
        print(f"Name: {result.name}")
        print(f"ID:   {result.id}")
        print(f"Enabled: {result.enabled}")
        ```

        ***

        ## 6. Validate the alert

        1. Wait a few minutes after creating the rule.
        2. Delete a test VM in the subscription.
        3. Confirm:
           * The Activity Log shows `Microsoft.Compute/virtualMachines/delete` with status `Succeeded`.
           * The configured Action Group (e.g., email) receives a notification.

        ***

        If you share how you authenticate to Azure (user vs service principal) and how you want alerts delivered (email, Teams, webhook), I can tailor the code and action group setup further.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        resource "azurerm_monitor_action_group" "VM_DELETE_ACTION_GROUP" {
          name                = "vm-delete-action-group"
          resource_group_name = "RESOURCE_GROUP_NAME" # replace with the RG where you want the action group
          short_name          = "vmdelete"

          email_receiver {
            name          = "primary-email"
            email_address = "ALERT_EMAIL_ADDRESS" # replace with the destination email
          }
        }

        resource "azurerm_monitor_activity_log_alert" "VM_DELETE_ALERT" {
          name                = "vm-delete-alert"
          resource_group_name = "RESOURCE_GROUP_NAME" # replace with the RG to store the alert resource
          scopes              = ["/subscriptions/SUBSCRIPTION_ID"] # replace with your subscription ID
          description         = "Alert on delete operations for Azure VMs"

          criteria {
            category       = "Administrative"
            operation_name = "Microsoft.Compute/virtualMachines/delete"
          }

          action {
            action_group_id = azurerm_monitor_action_group.VM_DELETE_ACTION_GROUP.id
          }

          tags = {
            Environment = "ENVIRONMENT_TAG" # optional, replace as needed
          }
        }
        ```

        This change does not force replacement of existing VMs; it only creates/updates monitoring resources (the alert and action group), which is safe to apply without VM downtime.

        To verify, `terraform plan` should show creation (or in-place update) of `azurerm_monitor_activity_log_alert.VM_DELETE_ALERT` (and `azurerm_monitor_action_group.VM_DELETE_ACTION_GROUP` if new), with `criteria.operation_name` set to `"Microsoft.Compute/virtualMachines/delete"`.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>

### Additional Reading:

* [https://docs.microsoft.com/en-us/azure/azure-monitor/platform/alerts-activity-log](https://docs.microsoft.com/en-us/azure/azure-monitor/platform/alerts-activity-log)
* [https://docs.microsoft.com/en-us/azure/azure-monitor/platform/alerts-log](https://docs.microsoft.com/en-us/azure/azure-monitor/platform/alerts-log)
