DEV Community

Smallsun2025
Smallsun2025

Posted on

Deploy Azure Snapshot and Managed Image with Terraform

🧭 Introduction

When managing virtual machines in Azure, creating backups and reusable VM images is a crucial part of infrastructure lifecycle management. In this post, we’ll walk through how to use Terraform to create:

  • A Snapshot (point-in-time backup of a managed disk)
  • A Managed Image (used to create new VMs from a base configuration)

This is useful for both disaster recovery and automated environment deployment.


🗂 Project Structure

The Terraform project consists of four files:
azure-image-snapshot-demo/
├── main.tf # Resource definitions: snapshot + image
├── variables.tf # Input variables
├── terraform.tfvars # Variable values
├── outputs.tf # Exported resource IDs


🔧 Terraform Resource Overview

  1. Resource Group

hcl
resource "azurerm_resource_group" "rg" {
  name     = var.resource_group_name
  location = var.location
}

2. Managed Disk
resource "azurerm_managed_disk" "os_disk" {
  name                 = "demo-os-disk"
  location             = azurerm_resource_group.rg.location
  resource_group_name  = azurerm_resource_group.rg.name
  storage_account_type = "Standard_LRS"
  create_option        = "Empty"
  disk_size_gb         = 30
}

3. Snapshot
resource "azurerm_snapshot" "vm_snapshot" {
  name                = "demo-vm-snapshot"
  location            = azurerm_resource_group.rg.location
  resource_group_name = azurerm_resource_group.rg.name
  create_option       = "Copy"
  source_uri          = azurerm_managed_disk.os_disk.id
}

4. Managed Image
resource "azurerm_image" "vm_image" {
  name                = "demo-vm-image"
  location            = azurerm_resource_group.rg.location
  resource_group_name = azurerm_resource_group.rg.name

  os_disk {
    os_type          = "Linux"
    os_state         = "Generalized"
    blob_uri         = null
    managed_disk_id  = azurerm_snapshot.vm_snapshot.id
  }
}
⚙️ How to Deploy (Optional)
az login
terraform init
terraform apply
terraform output

✅ Conclusion
With just a few lines of Terraform, we can automate the process of backing up a virtual machine and preparing a custom image. This is especially helpful when building golden images for reproducible environments or setting up disaster recovery strategies.

👉 GitHub Repository:
https://github.com/Smallsun2025/azure-image-snapshot-demo

If you found this helpful, please ⭐️ the repo or leave a comment!
Enter fullscreen mode Exit fullscreen mode

Top comments (0)