> ## 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 audit compute vms without backups remediation

### Triage and Remediation

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

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        To remediate the misconfiguration of virtual machines not having backups in AZURE using the AZURE console, follow these steps:

        1. Log in to the AZURE portal.
        2. In the left-hand menu, click on "Virtual machines".
        3. Select the virtual machine that needs to be backed up.
        4. In the virtual machine overview page, click on "Backup" under "Operations".
        5. In the "Backup" page, click on "Configure Backup".
        6. In the "Backup policy" page, click on "Create a new policy".
        7. In the "New policy" page, select the backup frequency, retention range, and other backup settings.
        8. Click on "OK" to create the backup policy.
        9. In the "Backup" page, click on "Enable Backup" to enable backup for the virtual machine.
        10. Review the backup policy and click on "OK".

        Once you have completed these steps, the virtual machine will be backed up according to the policy you have set up. You can also verify the backup status of the virtual machine by going to the "Backup" page and checking the backup status.

        #
      </Accordion>

      <Accordion title="Using CLI">
        To remediate the misconfiguration "Virtual Machines Should Have Backups" for Azure using Azure CLI, follow the below steps:

        1. Open the Azure CLI in your terminal or command prompt.

        2. Login to your Azure account using the command below:

           ```bash theme={null}
           az login
           ```

        3. Once you are logged in, select the Azure subscription in which the virtual machines are present using the command below:

           ```bash theme={null}
           az account set --subscription <subscription_id>
           ```

           Replace `<subscription_id>` with the ID of your Azure subscription.

        4. To enable backups for a virtual machine, use the following command:

           ```bash theme={null}
           az backup enable-for-vm --resource-group <resource_group_name> --vault-name <vault_name> --name <vm_name>
           ```

           Replace `<resource_group_name>` with the name of the resource group in which the virtual machine is present, `<vault_name>` with the name of the backup vault in which the backups will be stored, and `<vm_name>` with the name of the virtual machine for which you want to enable backups.

        5. Once the backups are enabled, you can configure the backup policy for the virtual machine using the following command:

           ```bash theme={null}
           az backup policy set --policy-name <policy_name> --resource-group <resource_group_name> --vault-name <vault_name> --backup-management-type AzureIaasVM --item-name <vm_name>
           ```

           Replace `<policy_name>` with the name of the backup policy that you want to apply, `<resource_group_name>` with the name of the resource group in which the virtual machine is present, `<vault_name>` with the name of the backup vault in which the backups will be stored, and `<vm_name>` with the name of the virtual machine for which you want to configure the backup policy.

        6. After the backup policy is set, you can trigger the backup of the virtual machine using the following command:

           ```bash theme={null}
           az backup protection enable-for-vm --resource-group <resource_group_name> --vault-name <vault_name> --policy-name <policy_name> --vm-name <vm_name>
           ```

           Replace `<resource_group_name>` with the name of the resource group in which the virtual machine is present, `<vault_name>` with the name of the backup vault in which the backups will be stored, `<policy_name>` with the name of the backup policy that you have configured, and `<vm_name>` with the name of the virtual machine for which you want to trigger the backup.

        7. Once the backup is completed, you can verify the backup status of the virtual machine using the following command:

           ```bash theme={null}
           az backup job list --resource-group <resource_group_name> --vault-name <vault_name> --output table
           ```

           Replace `<resource_group_name>` with the name of the resource group in which the virtual machine is present, and `<vault_name>` with the name of the backup vault in which the backups are stored.

        By following the above steps, you can remediate the misconfiguration "Virtual Machines Should Have Backups" for Azure using Azure CLI.
      </Accordion>

      <Accordion title="Using Python">
        To remediate the misconfiguration of virtual machines not having backups in Azure using Python, follow these steps:

        1. Import the necessary modules:

        ```python theme={null}
        from azure.common.credentials import ServicePrincipalCredentials
        from azure.mgmt.compute import ComputeManagementClient
        from azure.mgmt.resource import ResourceManagementClient
        from azure.mgmt.recoveryservices import RecoveryServicesClient
        from azure.mgmt.recoveryservicesbackup import RecoveryServicesBackupClient
        from azure.mgmt.recoveryservicesbackup.models import BackupRequestResource, BackupRequest, BackupRequestProperties, BackupRequestHeaders, BackupRequestVaultIdentity
        from azure.mgmt.recoveryservicesbackup.models import BackupRequestResourceGroupDetails, BackupRequestResourceDetails, BackupRequestResourceOptions, BackupRequestResourceItem
        from azure.mgmt.recoveryservicesbackup.models import BackupRequestResourceConfigDetails, BackupRequestResourceConfigDetailsDisk, BackupRequestResourceConfigDetailsFileFolder
        ```

        2. Authenticate to Azure using Service Principal credentials:

        ```python theme={null}
        # Set the Azure credentials
        subscription_id = 'your-subscription-id'
        client_id = 'your-client-id'
        client_secret = 'your-client-secret'
        tenant_id = 'your-tenant-id'

        # Authenticate to Azure
        credentials = ServicePrincipalCredentials(
            client_id=client_id,
            secret=client_secret,
            tenant=tenant_id
        )
        ```

        3. Create a Compute Management Client and a Recovery Services Backup Client:

        ```python theme={null}
        # Create a Compute Management Client
        compute_client = ComputeManagementClient(credentials, subscription_id)

        # Create a Recovery Services Backup Client
        backup_client = RecoveryServicesBackupClient(credentials, subscription_id)
        ```

        4. Get the list of virtual machines in the Azure subscription:

        ```python theme={null}
        # Get the list of virtual machines
        vm_list = compute_client.virtual_machines.list_all()
        ```

        5. For each virtual machine, check if it has a backup policy assigned. If not, create a backup policy and associate it with the virtual machine:

        ```python theme={null}
        # For each virtual machine, check if it has a backup policy assigned
        for vm in vm_list:
            # Get the backup policy for the virtual machine
            backup_policy = backup_client.backup_policies.get(
                vm.id,
                "DefaultPolicy"
            )

            # If the virtual machine does not have a backup policy assigned, create one and associate it with the virtual machine
            if backup_policy is None:
                # Create a backup policy
                backup_policy = backup_client.backup_policies.create_or_update(
                    vm.id,
                    "DefaultPolicy",
                    {
                        "policyType": "Simple",
                        "schedulePolicy": {
                            "scheduleRunFrequency": "Daily",
                            "scheduleRunDays": [
                                "Monday",
                                "Tuesday",
                                "Wednesday",
                                "Thursday",
                                "Friday",
                                "Saturday",
                                "Sunday"
                            ],
                            "scheduleRunTimes": [
                                "00:00"
                            ]
                        },
                        "retentionPolicy": {
                            "retentionPolicyType": "LongTerm",
                            "retentionDuration": {
                                "count": 365,
                                "durationType": "Days"
                            }
                        }
                    }
                )

                # Associate the backup policy with the virtual machine
                backup_client.protection_intent_items.create_or_update(
                    vm.id,
                    "DefaultPolicy",
                    {
                        "properties": {
                            "policyId": backup_policy.id
                        }
                    }
                )
        ```

        6. Once the backup policy is assigned to the virtual machine, it will start taking backups automatically based on the schedule specified in the policy.

        Note: This is just an example of how to remediate the misconfiguration of virtual machines not having backups in Azure using Python. The code may need to be modified based on your specific requirements and environment.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        resource "azurerm_linux_virtual_machine" "VM_WITH_BACKUP" {
          name                = "VM-NAME"
          resource_group_name = azurerm_resource_group.RG.name
          location            = azurerm_resource_group.RG.location
          size                = "Standard_DS1_v2"

          admin_username                  = "ADMIN_USERNAME"
          network_interface_ids           = [azurerm_network_interface.VM_NIC.id]
          disable_password_authentication = true

          admin_ssh_key {
            username   = "ADMIN_USERNAME"
            public_key = file("PATH/TO/SSH_PUBLIC_KEY")
          }

          os_disk {
            caching              = "ReadWrite"
            storage_account_type = "Standard_LRS"
          }

          source_image_reference {
            publisher = "Canonical"
            offer     = "0001-com-ubuntu-server-focal"
            sku       = "20_04-lts"
            version   = "latest"
          }
        }

        resource "azurerm_recovery_services_vault" "VM_BACKUP_VAULT" {
          name                = "RSV-NAME"
          location            = azurerm_resource_group.RG.location
          resource_group_name = azurerm_resource_group.RG.name
          sku                 = "Standard"

          soft_delete_enabled = true
        }

        resource "azurerm_backup_policy_vm" "VM_BACKUP_POLICY" {
          name                = "VM-BACKUP-POLICY-NAME"
          resource_group_name = azurerm_resource_group.RG.name
          recovery_vault_name = azurerm_recovery_services_vault.VM_BACKUP_VAULT.name

          timezone = "UTC"

          backup {
            frequency = "Daily"
            time      = "23:00"
          }

          retention_daily {
            count = 30
          }

          # Add weekly/monthly/yearly retention as required by your compliance:
          # retention_weekly { ... }
          # retention_monthly { ... }
          # retention_yearly { ... }
        }

        resource "azurerm_backup_protected_vm" "VM_BACKUP_PROTECTION" {
          resource_group_name = azurerm_resource_group.RG.name
          recovery_vault_name = azurerm_recovery_services_vault.VM_BACKUP_VAULT.name
          source_vm_id        = azurerm_linux_virtual_machine.VM_WITH_BACKUP.id
          backup_policy_id    = azurerm_backup_policy_vm.VM_BACKUP_POLICY.id
        }
        ```

        Substitute:

        * `VM-NAME` with your VM name.
        * `RG` with your resource group resource name.
        * `VM_NIC` with your NIC resource name.
        * `ADMIN_USERNAME`, `PATH/TO/SSH_PUBLIC_KEY` with your values.
        * `RSV-NAME` and `VM-BACKUP-POLICY-NAME` with your desired vault and policy names.

        This change does not replace the VM; it adds backup protection via a Recovery Services vault and backup policy.

        Verification: `terraform plan` should show creation of `azurerm_recovery_services_vault.VM_BACKUP_VAULT`, `azurerm_backup_policy_vm.VM_BACKUP_POLICY`, and `azurerm_backup_protected_vm.VM_BACKUP_PROTECTION` with no VM replacement, only the association of the VM to the backup policy.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>
