Azure VM Image Builder

Earn 25 points (50 with Pro) in two steps

  1. ① Read through the lesson — each section gets a ✓ as you scroll through it.
  2. ② When every section has a ✓, tap Complete lesson.

0 of 13 read · keep scrolling

✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro

Azure VM Image Builder: Mastering Custom Image Creation for AVD

Introduction: Why Image Management Matters

In the context of Azure Virtual Desktop (AVD), the session host is the engine that drives the user experience. If your session hosts are slow to boot, missing critical applications, or plagued by configuration drift, your users will experience frustration, which directly impacts productivity. Managing these images manually—by logging into a VM, installing software, running Windows Updates, and then capturing the disk—is a process fraught with human error. It is slow, difficult to replicate, and nearly impossible to version control.

Azure VM Image Builder (AIB) is the solution to these operational challenges. Built on top of HashiCorp Packer, AIB provides a managed service that automates the creation of custom virtual machine images. Instead of manually maintaining "gold images," you define your image configuration in a template file. AIB then handles the heavy lifting: it spins up a temporary build VM, applies your customizations, runs your scripts, generalizes the image, and distributes it to your Azure Compute Gallery or as a managed image. Mastering this tool is essential for any engineer tasked with scaling AVD environments effectively.


Not read yet

Understanding the Architecture of Azure VM Image Builder

To effectively use AIB, you must understand the underlying workflow. It is not just a "script runner"; it is a managed service that abstracts away the complexity of VM orchestration.

The Component Workflow

  1. Source: You define a starting point, such as a Windows 10/11 multi-session image from the Azure Marketplace.
  2. Customization: This is where the work happens. You can run PowerShell scripts, install software, apply registry keys, or use configuration management tools like Ansible.
  3. Distribution: Once the image is built, AIB pushes it to a destination. The most common destination is the Azure Compute Gallery, which allows for versioning and global replication.

Callout: Image Builder vs. Manual Snapshots Manual snapshots involve taking a disk from an existing VM and creating an image from it. While simple, it is not idempotent. Every time you update the image, you have to manually repeat the steps. AIB is declarative; you define the state you want the image to reach, and the service ensures that every build starts from a clean slate. This eliminates "configuration creep," where an image slowly gathers unnecessary settings over time.


Not read yet

Getting Started: Preparing Your Environment

Before you can run your first build, you need to set up the necessary permissions and resources in your Azure subscription. AIB requires a user-assigned managed identity to interact with your resources.

Step 1: Create a User-Assigned Managed Identity

The service needs permission to read the source image and write the finished image to your gallery.

  1. Navigate to the Azure Portal and search for "Managed Identities."
  2. Create a new identity in your target resource group.
  3. Assign this identity the "Contributor" role on the resource group where your images will be stored.

Step 2: Set Up the Azure Compute Gallery

The Azure Compute Gallery is the recommended way to store and share your custom images. It provides a structured way to version your images (e.g., 1.0.0, 1.0.1) and enables replication to different Azure regions.

  • Create a new Gallery.
  • Create an Image Definition within that gallery. Ensure you select the correct operating system (e.g., Windows 10/11 Enterprise Multi-session) and the correct generation (Gen 2 is recommended for modern AVD hosts).

Not read yet

Constructing the Image Template

The core of AIB is the template file. While you can use the Azure Portal to build these, using JSON templates is the industry standard because it allows you to store your image configuration in source control (like GitHub or Azure DevOps).

Anatomy of an AIB Template

A template consists of three primary sections: source, customize, and distribute.

1. The Source Section

This tells AIB where to start. You can point to a specific Marketplace image or an existing image version in your gallery.

"source": {
    "type": "PlatformImage",
    "publisher": "MicrosoftWindowsDesktop",
    "offer": "windows-11",
    "sku": "win11-22h2-avd",
    "version": "latest"
}

2. The Customize Section

This is where you define the steps to modify the image. You can use multiple types of customizers:

  • PowerShell: Execute remote scripts to install software.
  • File: Copy configuration files or installation binaries from a storage account into the image.
  • WindowsUpdate: A dedicated customizer that automatically runs Windows Update on the image before finalization.

3. The Distribute Section

This defines where the finished image goes. You should always distribute to the Azure Compute Gallery to take advantage of versioning.

Note: Always use the WindowsUpdate customizer in your AIB templates. It is significantly more efficient than running manual Windows Update scripts, as it handles reboots and service interruptions gracefully within the build process.


Not read yet

Practical Example: Building an AVD Host Image

Let’s walk through a concrete example of creating an image that installs Google Chrome and applies a specific registry setting for AVD optimization.

Step 1: The Script

First, create a script named install_apps.ps1:

# Install Chrome
$installer = "chrome_installer.exe"
Start-Process -FilePath $installer -ArgumentList "/silent /install" -Wait

# Disable unnecessary services
Set-Service -Name "MapsBroker" -StartupType Disabled

Step 2: The Template Configuration

You would define your template with a customizer pointing to this script:

"customize": [
    {
        "type": "PowerShell",
        "name": "InstallApps",
        "scriptUri": "https://mystorageaccount.blob.core.windows.net/scripts/install_apps.ps1"
    },
    {
        "type": "WindowsUpdate",
        "searchCriteria": "IsInstalled=0",
        "filters": ["exclude:$_.Title -like '*Preview*'", "include:$true"]
    }
]

Step 3: Running the Build

You can submit this template to Azure using the Azure CLI:

az image builder create -n MyImageTemplate -g MyResourceGroup --template-path myTemplate.json --managed-identity /subscriptions/.../myIdentity
az image builder run -n MyImageTemplate -g MyResourceGroup

Not read yet

Best Practices for Image Maintenance

Managing images is not a "set it and forget it" task. As AVD requirements change, so must your images.

Versioning Strategy

Always use Semantic Versioning (SemVer) for your images in the Azure Compute Gallery. If you are making a minor change, like updating a single application, increment the patch version (1.0.1). If you are changing the underlying OS or making major architectural shifts, move to the next minor or major version (1.1.0 or 2.0.0).

Security Hardening

Never store credentials in your build scripts. If your installation scripts require access to private storage, use Shared Access Signatures (SAS) with short expiration times, or better yet, use the Managed Identity assigned to the Image Builder to grant access to your storage blobs.

Cleanup and Validation

AIB creates temporary resources in your subscription during the build. While the service cleans these up automatically, it is good practice to monitor your resource groups to ensure that failed builds do not leave behind orphaned managed disks or networking components.

Tip: Use a Build Subnet By default, AIB will create a virtual network for the build process. If your organization has strict networking requirements (e.g., forced tunneling or specific firewall rules), you should configure AIB to use a dedicated "Build Subnet" within your existing VNet. This ensures the build VM has the necessary connectivity to download updates and applications.


Not read yet

Common Pitfalls and Troubleshooting

Even with a robust tool, things can go wrong. Understanding these common issues will save you hours of debugging.

1. The "Hung" Build

If your build seems to be stuck for hours, it is almost always an issue with a script. PowerShell scripts that do not exit properly or that prompt for user input will cause the build process to wait indefinitely.

  • Solution: Always ensure your scripts are non-interactive. Use the -Wait parameter for installers and ensure your scripts return a success or failure exit code.

2. Networking Connectivity

If your image cannot reach the internet to download updates or packages, the build will fail.

  • Solution: Check your Network Security Groups (NSGs). Ensure that your build subnet has outbound access to the necessary Microsoft update endpoints and any third-party repositories your apps require.

3. Image Size Limitations

Managed images have size limits depending on the disk type. If your image becomes too large, you may encounter deployment issues.

  • Solution: Use the "DiskSizeGB" property in your template to increase the capacity of the OS disk, but be mindful of the cost and performance implications of larger disks.

Not read yet

Comparison: AIB vs. Traditional Automation

It is helpful to compare AIB against other methods of image creation to understand its unique value proposition.

Feature Manual Snapshot Packer (Self-Hosted) Azure VM Image Builder
Automation None High High
Infrastructure Manual Requires Build Server Fully Managed
Maintenance High Medium Low
Idempotency No Yes Yes
Versioning Manual Manual Built-in (Gallery)

As shown in the table, while a self-hosted Packer instance offers similar automation to AIB, it requires you to maintain the build server (the "Packer agent"). AIB removes this operational overhead entirely, making it the superior choice for most enterprise AVD deployments.


Advanced Customization: Integrating with Configuration Management

While PowerShell is excellent for simple tasks, larger organizations often use tools like Ansible or Chef for configuration management. AIB integrates seamlessly with these tools.

Using Ansible with AIB

You can include an Ansible provisioner in your AIB template. This allows you to define your image state using YAML playbooks. This is highly effective if you already have an existing library of playbooks used for your physical workstations or other cloud servers.

{
    "type": "Ansible",
    "playbookPath": "ansible/playbook.yml",
    "userVars": {
        "app_version": "2.4.0"
    }
}

This approach ensures that your AVD session hosts are consistent with your overall infrastructure-as-code strategy.


Not read yet

Security Considerations: The "Gold Image" Concept

In the world of VDI, the "Gold Image" is a security perimeter. If your image is compromised, every user who logs into a session host based on that image is potentially at risk.

Image Integrity

Always scan your images for vulnerabilities. While AIB doesn't have a built-in vulnerability scanner, you can integrate your build process with tools like Microsoft Defender for Cloud. Once an image is pushed to the Azure Compute Gallery, Defender can scan it for known vulnerabilities, ensuring that you do not deploy insecure images to your production environment.

Minimizing the Attack Surface

A common mistake is "over-installing." Avoid including tools or services in your base image that are not strictly necessary for the end-user experience. Every installed application is a potential attack vector. Use the principle of least privilege: if an application is only needed by the accounting department, do not include it in the base image used for the entire company. Instead, use MSIX App Attach to deliver applications dynamically.


Not read yet

Lifecycle Management of Images

Once you have mastered the build process, you need to manage the lifecycle of your images. An image that was created two years ago is a liability.

Deprecation and Retirement

The Azure Compute Gallery allows you to mark specific image versions as "deprecated." This prevents new session hosts from being created using that version, while still allowing existing hosts to function. This is a critical step in your patch management cycle.

Automated Cleanup

Implement a strategy to delete old image versions. Keeping hundreds of versions in your gallery increases storage costs and makes it difficult to track which image is the current "production" standard. A simple PowerShell script running on a schedule can identify and remove versions older than a specific date or beyond a certain count.


The Role of Image Builder in an AVD Strategy

AVD is not just about the session host; it is about the entire ecosystem. Image Builder should be viewed as one node in a larger automation pipeline.

  1. GitHub/Azure DevOps: Holds the source code for your scripts and the AIB JSON templates.
  2. Azure VM Image Builder: Acts as the "Compiler" that turns code into a deployable image.
  3. Azure Compute Gallery: Acts as the "Artifact Repository" where the finished images live.
  4. Terraform/Bicep: Uses the image ID from the gallery to deploy the actual AVD session host pools.

By connecting these four components, you create a "Push-Button" infrastructure. When a new version of an application is released, you update your script in Git, trigger the pipeline, and within minutes, you have a new image ready to be deployed to your AVD host pools.


Not read yet

Detailed Step-by-Step: Creating a New Image Version

Let’s walk through the exact steps for an engineer updating a production image.

  1. Update Scripts: Modify your local scripts to reflect the new application versions or configuration changes.
  2. Commit to Source Control: Push your changes to your Git repository. This serves as the audit trail for why the image was changed.
  3. Update Template: If necessary, update the imageTemplate.json to point to the new scripts or to change the base image version (e.g., updating from the May release of Windows to the June release).
  4. Trigger Build: Run the Azure CLI command to start the build.
  5. Verify Build: Monitor the build logs. If it fails, examine the output property of the AIB resource to identify the error.
  6. Testing: Once the build completes, create a "Test" host pool in AVD using the new image version. Have a small group of pilot users verify that their applications work as expected.
  7. Production Rollout: Once validated, update your production host pool deployment templates (Bicep/Terraform) to reference the new image version ID.

Not read yet

Common Questions (FAQ)

Q: Can I use AIB to create Linux images? A: Yes, AIB supports both Windows and Linux. The customization process for Linux uses shell scripts instead of PowerShell, but the workflow remains identical.

Q: What is the cost of using Azure VM Image Builder? A: AIB itself is a free service. You only pay for the underlying Azure resources consumed during the build process, such as the temporary VM, the storage for the image, and the networking components.

Q: How do I handle reboots during the build? A: AIB handles reboots automatically. If a script requires a restart, you can use the restart customizer in your template. The build process will pause, wait for the VM to come back online, and then continue with the next step.

Q: Can I use AIB with a Private Link? A: Yes, AIB supports Private Link, which is highly recommended for organizations with strict security requirements. This ensures that all image-related traffic stays within your private Azure network.


Not read yet

Key Takeaways

  1. Automation is Mandatory: Manual image creation is not sustainable for modern AVD environments. Azure VM Image Builder provides the automation necessary to ensure consistency and reliability.
  2. Declarative Configuration: Treat your image templates as code. Store them in version control to ensure you can roll back to a known-good state if a build fails or causes issues.
  3. The Azure Compute Gallery is Essential: Never rely on simple managed images. The gallery provides the versioning, replication, and lifecycle management features required for professional-grade deployments.
  4. Idempotency is the Goal: Your build scripts should be able to run multiple times without causing errors. Focus on creating scripts that check for existing configurations before applying changes.
  5. Security First: Use Managed Identities to handle permissions, and always scan your images for vulnerabilities. Your image is the foundation of your session host security.
  6. Integrate into the Pipeline: AIB is most powerful when used as part of a CI/CD pipeline. Automate the trigger of your builds whenever your application or configuration scripts change.
  7. Test Before Deploying: Always validate new images in a non-production host pool before updating your production environment. A failed image deployment can lead to widespread service outages.

By following these principles and leveraging the full capabilities of Azure VM Image Builder, you can transform your image management from a high-maintenance chore into a streamlined, automated, and secure foundation for your AVD infrastructure. Remember that the goal is to spend less time managing the "how" of your images and more time ensuring your users have a productive and responsive desktop experience.

Not read yet

Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.