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
Top comments (0)