DEV Community

Smallsun2025
Smallsun2025

Posted on

Create Azure Managed Image with Terraform

Automate Managed Image Creation from Windows VM with Terraform on Azure

πŸ“Œ 1. Introduction

Creating a reusable VM image is a key part of cloud infrastructure workflows. In this tutorial, we’ll use Terraform to automate the process of deploying a Windows Virtual Machine (VM), preparing it with necessary configurations, and capturing a Managed Image from it. This is especially useful for building base images for application servers or golden images for dev/test environments.

πŸ“ 2. Project Structure

The repository contains the following Terraform files:
azure-windows-image/
β”œβ”€β”€ main.tf # Core resource definitions
β”œβ”€β”€ variables.tf # Input variables
β”œβ”€β”€ terraform.tfvars # Actual variable values
β”œβ”€β”€ outputs.tf # Outputs like image ID
β”œβ”€β”€ sysprep-guide.txt # Reminder on how to generalize VM

πŸ”§ 3. Terraform Code Breakdown

This Terraform configuration includes:

  • Resource Group – a container for all related Azure resources
  • Virtual Network & Subnet – basic network setup
  • Windows Virtual Machine – used as the base image
  • Managed Image Resource – created from the generalized VM disk
  • Startup script (optional) – to configure software before capturing

Key snippet to define a managed image:


hcl
resource "azurerm_image" "managed_image" {
  name                = var.image_name
  location            = azurerm_resource_group.rg.location
  resource_group_name = azurerm_resource_group.rg.name

  os_disk {
    os_type  = "Windows"
    os_state = "Generalized"
    blob_uri = azurerm_virtual_machine.vm.storage_os_disk[0].vhd_uri
    caching  = "ReadWrite"
  }
}

πŸ“¦ 4. Deployment Steps

1.Login to Azure CLI
az login

2.Initialize Terraform
terraform init

3.Review the execution plan
terraform plan

4.Apply the configuration
terraform apply

5.Generalize the VM using sysprep
Log in to the VM using RDP and run:
C:\Windows\System32\Sysprep\Sysprep.exe /oobe /generalize /shutdown
This will shut down and prepare the VM for image capture.

6.Run apply again to capture image
After the VM is generalized and shut down:
terraform apply -auto-approve


7.Get the image output
Terraform will output the image ID or name, which can be used for future VM creation.

βœ… 5. Conclusion

With a few lines of Terraform and a bit of sysprep preparation, you’ve successfully created a reusable Windows managed image on Azure. This is an essential skill for building consistent environments across dev, test, and production.

πŸ”œ Coming Next...

Creating VMs from Managed Images

Adding custom tags and encryption

Building a golden image pipeline with Packer + Terraform

Enter fullscreen mode Exit fullscreen mode

Top comments (0)