Quickstart: Apoie uma máquina virtual em Azure com um modelo ARMQuickstart: Back up a virtual machine in Azure with an ARM template

O Azure Backup apoia máquinas e aplicações no local e VMs Azure.Azure Backup backs up on-premises machines and apps, and Azure VMs. Este artigo mostra-lhe como fazer o back up de um Azure VM com um modelo Azure Resource Manager (modelo ARM) e Azure PowerShell.This article shows you how to back up an Azure VM with an Azure Resource Manager template (ARM template) and Azure PowerShell. Este quickstart foca-se no processo de implantação de um modelo ARM para criar um cofre dos Serviços de Recuperação.This quickstart focuses on the process of deploying an ARM template to create a Recovery Services vault. Para obter mais informações sobre o desenvolvimento de modelos ARM, consulte a documentação do Gestor de Recursos Azure e a referência do modelo.For more information on developing ARM templates, see the Azure Resource Manager documentation and the template reference.

Um modelo do ARM é um ficheiro JavaScript Object Notation (JSON) que define a infraestrutura e a configuração do seu projeto.An ARM template is a JavaScript Object Notation (JSON) file that defines the infrastructure and configuration for your project. O modelo utiliza sintaxe declarativa.The template uses declarative syntax. Em sintaxe declarativa o programador descreve a implementação pretendida sem escrever a sequência de comandos de programação para criar a implementação.In declarative syntax, you describe your intended deployment without writing the sequence of programming commands to create the deployment.

Um cofre dos Serviços de Recuperação é um recipiente lógico que armazena dados de backup para recursos protegidos, como os VMs Azure.A Recovery Services vault is a logical container that stores backup data for protected resources, such as Azure VMs. Quando um trabalho de reserva funciona, cria um ponto de recuperação dentro do cofre dos Serviços de Recuperação.When a backup job runs, it creates a recovery point inside the Recovery Services vault. Em seguida, pode utilizar um destes pontos de recuperação para restaurar dados para um determinado ponto no tempo.You can then use one of these recovery points to restore data to a given point in time. Em alternativa, pode apoiar um VM utilizando a Azure PowerShell,o Azure CLI,ou no portal Azure.Alternatively, you can back up a VM using Azure PowerShell, the Azure CLI, or in the Azure portal.

Se o seu ambiente cumpre os pré-requisitos e se está familiarizado com a utilização de modelos ARM, selecione o botão Implementar no Azure.If your environment meets the prerequisites and you're familiar with using ARM templates, select the Deploy to Azure button. O modelo será aberto no portal do Azure.The template will open in the Azure portal.

Implementar no AzureDeploy to Azure

Rever o modeloReview the template

O modelo utilizado neste arranque rápido é de Azure quickstart Templates.The template used in this quickstart is from Azure quickstart Templates. Este modelo permite-lhe implementar um cofre simples do Windows VM e dos Serviços de Recuperação configurado com a DefaultPolicy for Protection.This template allows you to deploy simple Windows VM and Recovery Services vault configured with the DefaultPolicy for Protection.

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "projectName": {
      "type": "string",
      "maxLength": 8,
      "metadata": {
        "description": "Specifies a name for generating resource names."
      }
    },
    "location": {
      "type": "string",
      "defaultValue": "[resourceGroup().location]",
      "metadata": {
        "description": "Specifies the location for all resources."
      }
    },
    "adminUsername": {
      "type": "string",
      "metadata": {
        "description": "Specifies the administrator username for the Virtual Machine."
      }
    },
    "adminPassword": {
      "type": "securestring",
      "metadata": {
        "description": "Specifies the administrator password for the Virtual Machine."
      }
    },
    "dnsLabelPrefix": {
      "type": "string",
      "metadata": {
        "description": "Specifies the unique DNS Name for the Public IP used to access the Virtual Machine."
      }
    },
    "vmSize": {
      "type": "string",
      "defaultValue": "Standard_A2",
      "metadata": {
        "description": "Virtual machine size."
      }
    },
    "windowsOSVersion": {
      "type": "string",
      "defaultValue": "2016-Datacenter",
      "allowedValues": [
        "2008-R2-SP1",
        "2012-Datacenter",
        "2012-R2-Datacenter",
        "2016-Nano-Server",
        "2016-Datacenter-with-Containers",
        "2016-Datacenter"
      ],
      "metadata": {
        "description": "Specifies the Windows version for the VM. This will pick a fully patched image of this given Windows version. Allowed values: 2008-R2-SP1, 2012-Datacenter, 2012-R2-Datacenter, 2016-Nano-Server, 2016-Datacenter-with-Containers, 2016-Datacenter."
      }
    }
  },
  "variables": {
    "storageAccountName": "[concat(parameters('projectName'), 'store')]",
    "networkInterfaceName": "[concat(parameters('projectName'), '-nic')]",
    "vNetAddressPrefix": "10.0.0.0/16",
    "vNetSubnetName": "default",
    "vNetSubnetAddressPrefix": "10.0.0.0/24",
    "publicIPAddressName": "[concat(parameters('projectName'), '-ip')]",
    "vmName": "[concat(parameters('projectName'), '-vm')]",
    "vNetName": "[concat(parameters('projectName'), '-vnet')]",
    "vaultName": "[concat(parameters('projectName'), '-vault')]",
    "backupFabric": "Azure",
    "backupPolicyName": "DefaultPolicy",
    "protectionContainer": "[concat('iaasvmcontainer;iaasvmcontainerv2;', resourceGroup().name, ';', variables('vmName'))]",
    "protectedItem": "[concat('vm;iaasvmcontainerv2;', resourceGroup().name, ';', variables('vmName'))]",
    "networkSecurityGroupName": "default-NSG"
  },
  "resources": [
    {
      "type": "Microsoft.Storage/storageAccounts",
      "apiVersion": "2019-06-01",
      "name": "[variables('storageAccountName')]",
      "location": "[parameters('location')]",
      "sku": {
        "name": "Standard_LRS"
      },
      "kind": "Storage",
      "properties": {}
    },
    {
      "type": "Microsoft.Network/publicIPAddresses",
      "apiVersion": "2020-06-01",
      "name": "[variables('publicIPAddressName')]",
      "location": "[parameters('location')]",
      "properties": {
        "publicIPAllocationMethod": "Dynamic",
        "dnsSettings": {
          "domainNameLabel": "[parameters('dnsLabelPrefix')]"
        }
      }
    },
    {
      "comments": "Default Network Security Group for template",
      "type": "Microsoft.Network/networkSecurityGroups",
      "apiVersion": "2020-06-01",
      "name": "[variables('networkSecurityGroupName')]",
      "location": "[parameters('location')]",
      "properties": {
        "securityRules": [
          {
            "name": "default-allow-3389",
            "properties": {
              "priority": 1000,
              "access": "Allow",
              "direction": "Inbound",
              "destinationPortRange": "3389",
              "protocol": "Tcp",
              "sourceAddressPrefix": "*",
              "sourcePortRange": "*",
              "destinationAddressPrefix": "*"
            }
          }
        ]
      }
    },
    {
      "type": "Microsoft.Network/virtualNetworks",
      "apiVersion": "2020-06-01",
      "name": "[variables('vNetName')]",
      "location": "[parameters('location')]",
      "dependsOn": [
        "[resourceId('Microsoft.Network/networkSecurityGroups', variables('networkSecurityGroupName'))]"
      ],
      "properties": {
        "addressSpace": {
          "addressPrefixes": [
            "[variables('vNetAddressPrefix')]"
          ]
        },
        "subnets": [
          {
            "name": "[variables('vNetSubnetName')]",
            "properties": {
              "addressPrefix": "[variables('vNetSubnetAddressPrefix')]",
              "networkSecurityGroup": {
                "id": "[resourceId('Microsoft.Network/networkSecurityGroups', variables('networkSecurityGroupName'))]"
              }
            }
          }
        ]
      }
    },
    {
      "type": "Microsoft.Network/networkInterfaces",
      "apiVersion": "2020-06-01",
      "name": "[variables('networkInterfaceName')]",
      "location": "[parameters('location')]",
      "dependsOn": [
        "[resourceId('Microsoft.Network/publicIPAddresses', variables('publicIPAddressName'))]",
        "[resourceId('Microsoft.Network/virtualNetworks', variables('vNetName'))]"
      ],
      "properties": {
        "ipConfigurations": [
          {
            "name": "ipconfig1",
            "properties": {
              "privateIPAllocationMethod": "Dynamic",
              "publicIPAddress": {
                "id": "[resourceId('Microsoft.Network/publicIPAddresses',variables('publicIPAddressName'))]"
              },
              "subnet": {
                "id": "[resourceId('Microsoft.Network/virtualNetworks/subnets', variables('vNetName'), variables('vNetSubnetName'))]"
              }
            }
          }
        ]
      }
    },
    {
      "type": "Microsoft.Compute/virtualMachines",
      "apiVersion": "2020-06-01",
      "name": "[variables('vmName')]",
      "location": "[parameters('location')]",
      "dependsOn": [
        "[resourceId('Microsoft.Storage/storageAccounts', variables('storageAccountName'))]",
        "[resourceId('Microsoft.Network/networkInterfaces', variables('networkInterfaceName'))]"
      ],
      "properties": {
        "hardwareProfile": {
          "vmSize": "[parameters('vmSize')]"
        },
        "osProfile": {
          "computerName": "[variables('vmName')]",
          "adminUsername": "[parameters('adminUsername')]",
          "adminPassword": "[parameters('adminPassword')]"
        },
        "storageProfile": {
          "imageReference": {
            "publisher": "MicrosoftWindowsServer",
            "offer": "WindowsServer",
            "sku": "[parameters('windowsOSVersion')]",
            "version": "latest"
          },
          "osDisk": {
            "createOption": "FromImage"
          },
          "dataDisks": [
            {
              "diskSizeGB": 1023,
              "lun": 0,
              "createOption": "Empty"
            }
          ]
        },
        "networkProfile": {
          "networkInterfaces": [
            {
              "id": "[resourceId('Microsoft.Network/networkInterfaces',variables('networkInterfaceName'))]"
            }
          ]
        },
        "diagnosticsProfile": {
          "bootDiagnostics": {
            "enabled": true,
            "storageUri": "[reference(resourceId('Microsoft.Storage/storageAccounts', variables('storageAccountName'))).primaryEndpoints.blob]"
          }
        }
      }
    },
    {
      "type": "Microsoft.RecoveryServices/vaults",
      "apiVersion": "2020-02-02",
      "name": "[variables('vaultName')]",
      "location": "[parameters('location')]",
      "sku": {
        "name": "RS0",
        "tier": "Standard"
      },
      "properties": {}
    },
    {
      "type": "Microsoft.RecoveryServices/vaults/backupFabrics/protectionContainers/protectedItems",
      "apiVersion": "2020-02-02",
      "name": "[concat(variables('vaultName'), '/', variables('backupFabric'), '/', variables('protectionContainer'), '/', variables('protectedItem'))]",
      "dependsOn": [
        "[resourceId('Microsoft.Compute/virtualMachines', variables('vmName'))]",
        "[resourceId('Microsoft.RecoveryServices/vaults', variables('vaultName'))]"
      ],
      "properties": {
        "protectedItemType": "Microsoft.Compute/virtualMachines",
        "policyId": "[resourceId('Microsoft.RecoveryServices/vaults/backupPolicies', variables('vaultName'), variables('backupPolicyName'))]",
        "sourceResourceId": "[resourceId('Microsoft.Compute/virtualMachines', variables('vmName'))]"
      }
    }
  ]
}

Os recursos definidos no modelo são:The resources defined in the template are:

Implementar o modeloDeploy the template

Para implementar o modelo, selecione Experimente-o para abrir a Camada de Nuvem Azure e, em seguida, cole o seguinte script PowerShell na janela do reservatório.To deploy the template, select Try it to open the Azure Cloud Shell, and then paste the following PowerShell script into the shell window. Para colar o código, clique com o botão direito na janela da concha e, em seguida, selecione Pasta.To paste the code, right-click the shell window and then select Paste.

$projectName = Read-Host -Prompt "Enter a project name (limited to eight characters) that is used to generate Azure resource names"
$location = Read-Host -Prompt "Enter the location (for example, centralus)"
$adminUsername = Read-Host -Prompt "Enter the administrator username for the virtual machine"
$adminPassword = Read-Host -Prompt "Enter the administrator password for the virtual machine" -AsSecureString
$dnsPrefix = Read-Host -Prompt "Enter the unique DNS Name for the Public IP used to access the virtual machine"

$resourceGroupName = "${projectName}rg"
$templateUri = "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/101-recovery-services-create-vm-and-configure-backup/azuredeploy.json"

New-AzResourceGroup -Name $resourceGroupName -Location $location
New-AzResourceGroupDeployment -ResourceGroupName $resourceGroupName -TemplateUri $templateUri -projectName $projectName -adminUsername $adminUsername -adminPassword $adminPassword -dnsLabelPrefix $dnsPrefix

A Azure PowerShell é utilizado para implantar o modelo ARM neste arranque rápido.Azure PowerShell is used to deploy the ARM template in this quickstart. O portal Azure, Azure CLIe Rest API também podem ser usados para implantar modelos.The Azure portal, Azure CLI, and Rest API can also be used to deploy templates.

Validar a implementaçãoValidate the deployment

Iniciar uma tarefa de cópia de segurançaStart a backup job

O modelo cria um VM e permite voltar a ser o VM.The template creates a VM and enables back on the VM. Depois de implementar o modelo, tem de iniciar um trabalho de reserva.After you deploy the template, you need to start a backup job. Para obter mais informações, consulte Iniciar um trabalho de backup.For more information, see Start a backup job.

Monitorizar a tarefa de cópia de segurançaMonitor the backup job

Para monitorizar o trabalho de backup, consulte monitorar o trabalho de reserva.To monitor the backup job, see Monitor the backup job.

Limpar recursosClean up resources

Se já não precisar de fazer o reforço do VM, pode limpá-lo.If you no longer need to back up the VM, you can clean it up.

  • Se quiser experimentar restaurar o VM, ignore a limpeza.If you want to try out restoring the VM, skip the cleanup.
  • Se utilizar um VM existente, pode saltar o cmdlet final do Remove-AzResourceGroup para deixar o grupo de recursos e o VM no lugar.If you used an existing VM, you can skip the final Remove-AzResourceGroup cmdlet to leave the resource group and VM in place.

Desative a proteção, remova os pontos de restauro e o cofre.Disable protection, remove the restore points and vault. Em seguida, elimine o grupo de recursos e os recursos VM associados, da seguinte forma:Then delete the resource group and associated VM resources, as follows:

Disable-AzRecoveryServicesBackupProtection -Item $item -RemoveRecoveryPoints
$vault = Get-AzRecoveryServicesVault -Name "myRecoveryServicesVault"
Remove-AzRecoveryServicesVault -Vault $vault
Remove-AzResourceGroup -Name "myResourceGroup"

Passos seguintesNext steps

Neste início rápido, criou um cofre dos Serviços de Recuperação, ativou a proteção numa VM e criou o ponto de recuperação inicial.In this quickstart, you created a Recovery Services vault, enabled protection on a VM, and created the initial recovery point.