Edit

Share via


Quickstart: Back up a virtual machine in Azure with Terraform

In this quickstart, you create an Azure Windows virtual machine (VM) and associated resources using Terraform. An Azure Windows VM is a scalable computing resource that Azure provides. It's an on-demand, virtualized Windows server in the Azure cloud. You can use it to deploy, test, and run applications, among other things. In addition to the VM, this code also creates a virtual network, subnet, public IP, network security group, network interface, storage account, Azure Backup recovery services vault, and Backup policy.

Terraform enables the definition, preview, and deployment of cloud infrastructure. Using Terraform, you create configuration files using HCL syntax. The HCL syntax allows you to specify the cloud provider - such as Azure - and the elements that make up your cloud infrastructure. After you create your configuration files, you create an execution plan that allows you to preview your infrastructure changes before they're deployed. Once you verify the changes, you apply the execution plan to deploy the infrastructure.

In this article, you learn how to:

  • Create an Azure resource group with a unique name.
  • Create a virtual network with a unique name and a specified address space.
  • Create a subnet within the virtual network with a unique name and a specified address prefix.
  • Create a public IP address with a unique name.
  • Create a network security group with two security rules for remote desk protocol and web traffic.
  • Create a network interface with a unique name, and attach it to the subnet and public IP address.
  • Associate the network security group with the network interface.
  • Generate a random ID for a unique storage account name, and insert a storage account for boot diagnostics.
  • Create a Windows VM with a unique name, and generate a random password for the VM.
  • Create a Backup recovery services vault with a unique name.
  • Create a Backup policy for the VM with daily frequency and a retention period of seven days.
  • Protect the VM with the created Backup policy.

Prerequisites

Implement the Terraform code

The sample code for this article is located in the Azure Terraform GitHub repo. You can view the log file containing the test results from current and previous versions of Terraform. See more articles and sample code showing how to use Terraform to manage Azure resources.

  1. Create a directory in which to test and run the sample Terraform code, and make it the current directory.

  2. Create a file named main.tf, and insert the following code:

    resource "random_pet" "rg_name" {
      prefix = var.resource_group_name_prefix
    }
    
    resource "azurerm_resource_group" "rg" {
      location = var.resource_group_location
      name     = random_pet.rg_name.id
    }
    
    resource "random_string" "name" {
      length  = 12
      lower   = true
      upper   = false
      numeric = false
      special = false
    }
    
    # Create virtual network
    resource "azurerm_virtual_network" "my_terraform_network" {
      name                = "${random_string.name.id}-vnet"
      address_space       = ["10.0.0.0/16"]
      location            = azurerm_resource_group.rg.location
      resource_group_name = azurerm_resource_group.rg.name
    }
    
    # Create subnet
    resource "azurerm_subnet" "my_terraform_subnet" {
      name                 = "${random_string.name.id}-subnet"
      resource_group_name  = azurerm_resource_group.rg.name
      virtual_network_name = azurerm_virtual_network.my_terraform_network.name
      address_prefixes     = ["10.0.1.0/24"]
    }
    
    # Create public IPs
    resource "azurerm_public_ip" "my_terraform_public_ip" {
      name                = "${random_string.name.id}-public-ip"
      location            = azurerm_resource_group.rg.location
      resource_group_name = azurerm_resource_group.rg.name
      allocation_method   = "Dynamic"
    }
    
    # Create Network Security Group and rules
    resource "azurerm_network_security_group" "my_terraform_nsg" {
      name                = "${random_string.name.id}-nsg"
      location            = azurerm_resource_group.rg.location
      resource_group_name = azurerm_resource_group.rg.name
    
      security_rule {
        name                       = "RDP"
        priority                   = 1000
        direction                  = "Inbound"
        access                     = "Allow"
        protocol                   = "*"
        source_port_range          = "*"
        destination_port_range     = "3389"
        source_address_prefix      = "*"
        destination_address_prefix = "*"
      }
      security_rule {
        name                       = "web"
        priority                   = 1001
        direction                  = "Inbound"
        access                     = "Allow"
        protocol                   = "Tcp"
        source_port_range          = "*"
        destination_port_range     = "80"
        source_address_prefix      = "*"
        destination_address_prefix = "*"
      }
    }
    
    # Create network interface
    resource "azurerm_network_interface" "my_terraform_nic" {
      name                = "${random_string.name.id}-nic"
      location            = azurerm_resource_group.rg.location
      resource_group_name = azurerm_resource_group.rg.name
    
      ip_configuration {
        name                          = "my_nic_configuration"
        subnet_id                     = azurerm_subnet.my_terraform_subnet.id
        private_ip_address_allocation = "Dynamic"
        public_ip_address_id          = azurerm_public_ip.my_terraform_public_ip.id
      }
    }
    
    # Connect the security group to the network interface
    resource "azurerm_network_interface_security_group_association" "example" {
      network_interface_id      = azurerm_network_interface.my_terraform_nic.id
      network_security_group_id = azurerm_network_security_group.my_terraform_nsg.id
    }
    
    # Create storage account for boot diagnostics
    resource "azurerm_storage_account" "my_storage_account" {
      name                     = "diag${random_id.random_id.hex}"
      location                 = azurerm_resource_group.rg.location
      resource_group_name      = azurerm_resource_group.rg.name
      account_tier             = "Standard"
      account_replication_type = "LRS"
    }
    
    # Create virtual machine
    resource "azurerm_windows_virtual_machine" "main" {
      name                              = "${random_string.name.id}-vm"
      admin_username                    = "azureuser"
      admin_password                    = random_password.password.result
      location                          = azurerm_resource_group.rg.location
      resource_group_name               = azurerm_resource_group.rg.name
      network_interface_ids             = [azurerm_network_interface.my_terraform_nic.id]
      size                              = "Standard_DS1_v2"
      vm_agent_platform_updates_enabled = true
    
      os_disk {
        name                 = "myOsDisk"
        caching              = "ReadWrite"
        storage_account_type = "Premium_LRS"
      }
    
      source_image_reference {
        publisher = "MicrosoftWindowsServer"
        offer     = "WindowsServer"
        sku       = "2022-datacenter-azure-edition"
        version   = "latest"
      }
    
    
      boot_diagnostics {
        storage_account_uri = azurerm_storage_account.my_storage_account.primary_blob_endpoint
      }
    }
    
    # Generate random text for a unique storage account name
    resource "random_id" "random_id" {
      keepers = {
        # Generate a new ID only when a new resource group is defined
        resource_group = azurerm_resource_group.rg.name
      }
    
      byte_length = 8
    }
    
    resource "random_password" "password" {
      length      = 20
      min_lower   = 1
      min_upper   = 1
      min_numeric = 1
      min_special = 1
      special     = true
    }
    
    resource "azurerm_recovery_services_vault" "example" {
      name                = "${random_string.name.id}-vault"
      resource_group_name = azurerm_resource_group.rg.name
      location            = azurerm_resource_group.rg.location
      sku                 = "Standard"
      soft_delete_enabled = var.soft_delete_enabled
    }
    
    resource "azurerm_backup_policy_vm" "example" {
      name                = "${random_string.name.id}-policy"
      resource_group_name = azurerm_resource_group.rg.name
      recovery_vault_name = azurerm_recovery_services_vault.example.name
    
      backup {
        frequency = "Daily"
        time      = "23:00"
      }
    
      retention_daily {
        count = 7
      }
    }
    
    resource "azurerm_backup_protected_vm" "example" {
      resource_group_name = azurerm_resource_group.rg.name
      recovery_vault_name = azurerm_recovery_services_vault.example.name
      source_vm_id        = azurerm_windows_virtual_machine.main.id
      backup_policy_id    = azurerm_backup_policy_vm.example.id
    }
    
  3. Create a file named outputs.tf, and insert the following code:

    output "resource_group_name" {
      value = azurerm_resource_group.rg.name
    }
    
    output "azurerm_recovery_services_vault_name" {
      value = azurerm_recovery_services_vault.example.name
    }
    
    output "azurerm_backup_policy_vm_name" {
      value = azurerm_backup_policy_vm.example.name
    }
    
    output "azurerm_windows_virtual_machine_name" {
      value = azurerm_windows_virtual_machine.main.name
    }
    
    output "public_ip_address" {
      value = azurerm_windows_virtual_machine.main.public_ip_address
    }
    
    output "admin_password" {
      sensitive = true
      value     = azurerm_windows_virtual_machine.main.admin_password
    }
    
  4. Create a file named providers.tf, and insert the following code:

    terraform {
      required_version = ">=1.0"
    
      required_providers {
        azurerm = {
          source  = "hashicorp/azurerm"
          version = "~>3.0"
        }
        random = {
          source  = "hashicorp/random"
          version = "~>3.0"
        }
      }
    }
    
    provider "azurerm" {
      features {
        recovery_service {
          vm_backup_stop_protection_and_retain_data_on_destroy = true
          purge_protected_items_from_vault_on_destroy          = true
        }
      }
    }
    
  5. Create a file named variables.tf, and insert the following code:

    variable "resource_group_location" {
      type        = string
      default     = "eastus"
      description = "Location of the resource group."
    }
    
    variable "resource_group_name_prefix" {
      type        = string
      default     = "rg"
      description = "Prefix of the resource group name that's combined with a random ID so name is unique in your Azure subscription."
    }
    
    variable "soft_delete_enabled" {
      type        = bool
      default     = false
      nullable    = false
      description = "Is soft delete enable for the recovery services vault?"
    }
    

Important

If you're using the 4.x azurerm provider, you must explicitly specify the Azure subscription ID to authenticate to Azure before running the Terraform commands.

One way to specify the Azure subscription ID without putting it in the providers block is to specify the subscription ID in an environment variable named ARM_SUBSCRIPTION_ID.

For more information, see the Azure provider reference documentation.

Initialize Terraform

Run terraform init to initialize the Terraform deployment. This command downloads the Azure provider required to manage your Azure resources.

terraform init -upgrade

Key points:

  • The -upgrade parameter upgrades the necessary provider plugins to the newest version that complies with the configuration's version constraints.

Create a Terraform execution plan

Run terraform plan to create an execution plan.

terraform plan -out main.tfplan

Key points:

  • The terraform plan command creates an execution plan, but doesn't execute it. Instead, it determines what actions are necessary to create the configuration specified in your configuration files. This pattern allows you to verify whether the execution plan matches your expectations before making any changes to actual resources.
  • The optional -out parameter allows you to specify an output file for the plan. Using the -out parameter ensures that the plan you reviewed is exactly what is applied.

Apply a Terraform execution plan

Run terraform apply to apply the execution plan to your cloud infrastructure.

terraform apply main.tfplan

Key points:

  • The example terraform apply command assumes you previously ran terraform plan -out main.tfplan.
  • If you specified a different filename for the -out parameter, use that same filename in the call to terraform apply.
  • If you didn't use the -out parameter, call terraform apply without any parameters.

Verify the results

  1. Get the Azure resource group name.

    resource_group_name = $(terraform outout -raw azurerm_resource_group_name)
    
  2. Get the Backup recovery services vault name.

    recovery_services_vault_name = $(terraform output -raw azurerm_recovery_services_vault_name)
    
  3. Get the Windows VM name.

    windows_virtual_machine_name = $(terraform output -raw azurerm_windows_virtual_machine_name)
    
  4. Run az backup protection backup-now to start a backup job.

    az backup protection backup-now --resource-group $resource_group_name \
                                    --vault-name $recovery_services_vault_name \
                                    --container-name $windows_virtual_machine_name \
                                    --item-name $windows_virtual_machine_name \
                                    --backup-management-type AzureIaaSVM
    
  5. Run az backup job list to monitor the backup job. When the Status of the backup job reports Completed, your VM is protected with Backup recovery services and has a full recovery point stored.

    az backup job list --resource-group $resource_group_name \
                       --vault-name $recovery_services_vault_name \
                       --output table
    

Clean up resources

When you no longer need the resources created via Terraform, do the following steps:

  1. Run terraform plan and specify the destroy flag.

    terraform plan -destroy -out main.destroy.tfplan
    

    Key points:

    • The terraform plan command creates an execution plan, but doesn't execute it. Instead, it determines what actions are necessary to create the configuration specified in your configuration files. This pattern allows you to verify whether the execution plan matches your expectations before making any changes to actual resources.
    • The optional -out parameter allows you to specify an output file for the plan. Using the -out parameter ensures that the plan you reviewed is exactly what is applied.
  2. Run terraform apply to apply the execution plan.

    terraform apply main.destroy.tfplan
    

Troubleshoot Terraform on Azure

Troubleshoot common problems when using Terraform on Azure.

Next steps