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

# Enable Instance Termination Notifications For Virtual Machine Scale Sets

### More Info:

Ensure that your Microsoft Azure virtual machine scale sets are configured to receive instance termination notifications through the Azure Metadata service and have a predefined delay timeout configured for the Terminate operation (event). The termination notifications are delivered through Scheduled Events, an Azure Metadata feature which sends termination notifications, and can also be used to delay impactful operations such as reboots and redeployments. The delay associated with the Terminate event will depend on the delay limit specified in the VM scale set model configuration.

### Risk Level

Medium

### Address

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 "Enable Instance Termination Notifications For Virtual Machine Scale Sets" in AZURE using the AZURE console:

        1. Open the AZURE portal and log in to your account.
        2. Navigate to the Virtual Machine Scale Sets blade.
        3. Select the Virtual Machine Scale Set for which you want to enable the instance termination notifications.
        4. In the Virtual Machine Scale Set blade, click on the "Auto Scale" option from the left-hand side menu.
        5. In the "Auto Scale" blade, click on the "Notifications" tab.
        6. In the "Notifications" tab, click on the "Add notification" button.
        7. In the "Add notification" blade, select "Email" as the notification type.
        8. Enter the email address of the recipient(s) who will receive the notification in the "Email addresses" field.
        9. In the "Email subject" field, enter a subject line for the notification email.
        10. In the "Email body" field, enter the message you want to include in the notification email.
        11. Click on the "OK" button to save the notification settings.

        That's it! You have now enabled the instance termination notifications for your Virtual Machine Scale Set in AZURE. Whenever an instance is terminated, the configured recipient(s) will receive an email notification.

        #
      </Accordion>

      <Accordion title="Using CLI">
        To remediate the misconfiguration "Enable Instance Termination Notifications For Virtual Machine Scale Sets" in Azure using Azure CLI, you can follow the below steps:

        Step 1: Open the Azure CLI command prompt or terminal.

        Step 2: Run the following command to enable the instance termination notifications for virtual machine scale sets:

        ```
        az monitor autoscale update --ids <resource-id> --add-notification email --email-administrator <email-address>
        ```

        Note: Replace `<resource-id>` with the resource ID of the virtual machine scale set and `<email-address>` with the email address of the administrator.

        Step 3: Verify the instance termination notification settings by running the following command:

        ```
        az monitor autoscale show --ids <resource-id>
        ```

        Note: Replace `<resource-id>` with the resource ID of the virtual machine scale set.

        Step 4: Ensure that the "notifications" property in the output of the above command contains the email address of the administrator.

        With these steps, you have successfully remediated the misconfiguration "Enable Instance Termination Notifications For Virtual Machine Scale Sets" in Azure using Azure CLI.
      </Accordion>

      <Accordion title="Using Python">
        To remediate the misconfiguration "Enable Instance Termination Notifications For Virtual Machine Scale Sets" for AZURE using Python, you can follow the below steps:

        1. Import the required libraries:

        ```python theme={null}
        from azure.mgmt.compute import ComputeManagementClient
        from azure.mgmt.monitor import MonitorManagementClient
        from azure.identity import DefaultAzureCredential
        from azure.mgmt.monitor.models import ActionGroup, ActionGroupPatchBody, ActionGroupResource
        ```

        2. Authenticate the client:

        ```python theme={null}
        credential = DefaultAzureCredential()
        compute_client = ComputeManagementClient(credential, subscription_id)
        monitor_client = MonitorManagementClient(credential, subscription_id)
        ```

        3. Get the VM Scale Set ID:

        ```python theme={null}
        vmss = compute_client.virtual_machine_scale_set_vms.list(resource_group_name, vm_scale_set_name)
        vmss_id = vmss.next().id
        ```

        4. Create an action group:

        ```python theme={null}
        action_group_name = "my_action_group"
        email_address = "youremail@example.com"
        sms_phone_number = "+1234567890"

        action_group = ActionGroup(
            group_short_name=action_group_name,
            enabled=True,
            email_receivers=[email_address],
            sms_receivers=[sms_phone_number],
        )

        monitor_client.action_groups.create_or_update(resource_group_name, action_group_name, action_group)
        ```

        5. Get the action group ID:

        ```python theme={null}
        action_group = monitor_client.action_groups.get(resource_group_name, action_group_name)
        action_group_id = action_group.id
        ```

        6. Enable termination notifications for the VM Scale Set:

        ```python theme={null}
        monitor_client.autoscale_settings.create_or_update(
            resource_group_name,
            vm_scale_set_name,
            "default",
            {
                "profiles": [
                    {
                        "name": "defaultProfile",
                        "capacity": {"minimum": "1", "maximum": "10", "default": "1"},
                        "rules": [
                            {
                                "metric_trigger": {
                                    "metric_name": "Percentage CPU",
                                    "metric_resource_uri": vmss_id,
                                    "time_grain": "PT1M",
                                    "statistic": "Average",
                                    "time_window": "PT5M",
                                    "time_aggregation": "Average",
                                    "operator": "GreaterThan",
                                    "threshold": 80,
                                },
                                "scale_action": {
                                    "direction": "Increase",
                                    "type": "ChangeCount",
                                    "value": "1",
                                    "cooldown": "PT5M",
                                },
                            }
                        ],
                        "notifications": [
                            {
                                "operation": "Terminate",
                                "email": {"send_to_subscription_administrator": True},
                                "action_group_id": action_group_id,
                            }
                        ],
                    }
                ]
            },
        )
        ```

        These steps will enable instance termination notifications for the specified VM Scale Set in Azure using Python.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        resource "azurerm_linux_virtual_machine_scale_set" "VMSS_NAME" {
          name                = "VMSS_NAME"                # replace with your VM scale set name
          location            = azurerm_resource_group.RG_NAME.location
          resource_group_name = azurerm_resource_group.RG_NAME.name
          sku                 = "Standard_DS2_v2"
          instances           = 3
          admin_username      = "ADMIN_USERNAME"
          # ... other required arguments (source_image_reference, network_interface, os_disk, etc.)

          termination_notification {
            enabled = true
            # Replace PT5M with your required delay before termination (ISO 8601 duration, max 15 minutes).
            # Example thresholds: PT30S, PT2M, PT10M
            timeout = "PT5M"
          }
        }
        ```

        If this is a `azurerm_windows_virtual_machine_scale_set`, use the same `termination_notification` block inside that resource instead.

        This change is in-place and does not force replacement of the VM scale set; existing instances will honor scheduled events after the model is updated.

        Verification: `terraform plan` should show the `termination_notification` block being added (or `enabled` changing to `true` and `timeout` to your chosen value) on the relevant `azurerm_*_virtual_machine_scale_set` resource, with no `-/+` replacement of the scale set.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>
