Skip to content
Back to Blog

Deploy Azure Virtual Desktop with Bicep or Terraform: A Minimal Setup

D
Founder and CEO, Atlas AVD··Updated
Deploy Azure Virtual Desktop with Bicep or Terraform: A Minimal Setup

To deploy Azure Virtual Desktop (AVD) with Bicep or Terraform, you define four things: a host pool, a desktop application group that points at it, a workspace that publishes the group, and session host VMs that join your directory and register with the pool using a registration token. The first three are a few dozen lines in either tool; the session hosts are where the real work is, because each one is a VM plus a directory join plus the AVD agent. Bicep needs no state file and supports every new AVD API on day one, while Terraform fits teams that already run Terraform for the rest of their estate.

The short version: Infrastructure as code (IaC) is the right way to build AVD: the host pool, application group, workspace, user assignment and session hosts, reviewed in a pull request and rebuilt the same way in any region. It's the wrong tool for what happens to that environment every day: rolling a new image onto hosts that have users on them, tuning session limits, helping a user who can't connect. Most teams end up with both: code for what exists, and an operations tool for what happens to it, with one clear owner for each setting.

This guide assumes you've deployed AVD once by hand. If you haven't, start with how to deploy AVD in under 30 minutes: the portal shows you every object before you put it in code.


The resources a minimal AVD deployment needs

ResourceWhat it doesBicep typeTerraform resource (azurerm)
Host poolThe group of session hosts, with its type (pooled or personal), load balancing and session limitMicrosoft.DesktopVirtualization/hostPoolsazurerm_virtual_desktop_host_pool
Registration tokenThe short-lived key a new session host uses to join the poolregistrationInfo on the host pool, read with listRegistrationTokens()azurerm_virtual_desktop_host_pool_registration_info
Application groupWhat users get from the pool: a full desktop, or RemoteAppsMicrosoft.DesktopVirtualization/applicationGroupsazurerm_virtual_desktop_application_group
WorkspaceWhat users see in Windows App; it lists your application groupsMicrosoft.DesktopVirtualization/workspacesazurerm_virtual_desktop_workspace plus azurerm_virtual_desktop_workspace_application_group_association
User assignmentThe Desktop Virtualization User role on the application group, for a security groupMicrosoft.Authorization/roleAssignmentsazurerm_role_assignment
Session hostsThe VMs, joined to Active Directory or Microsoft Entra ID, with the AVD agent registered to the poolMicrosoft.Compute/virtualMachines and extensionsazurerm_windows_virtual_machine and azurerm_virtual_machine_extension

The portal creates the desktop application group for you; in code you create it yourself. You also still need what sits underneath: a virtual network that can reach your domain controllers (or Entra ID only), an image, and FSLogix profile storage. Those are ordinary Azure resources and aren't AVD-specific, so this guide leaves them out.


Bicep or Terraform?

BicepTerraform
StateNone. Azure is the record of what existsA state file you store, lock and protect (usually an Azure Storage backend)
New AVD featuresAny API version, the day it shipsWhen the azurerm provider adds them; the azapi provider fills the gap
Preview a changeaz deployment group what-ifterraform plan
Removing what you deleted from codeOnly with deployment stacksBy default
Registration tokenRead at deploy time with listRegistrationTokens()A resource; the token is stored in state, so treat the state file as a secret
Beyond AzureAzure onlyEntra groups (azuread provider), DNS, GitHub and other clouds in the same run
Best forAzure-only teams, and anyone who wants Microsoft's AVD samples as a starting pointTeams already running Terraform, or managing Entra and other systems alongside AVD

Both are fully supported ways to build AVD. Pick the one your team already uses for the rest of Azure: a second IaC language for one workload costs more than either tool's weaknesses.

You don't have to write either from scratch. Microsoft's Azure Virtual Desktop landing zone accelerator has reference deployments in both, and Azure Verified Modules publishes a supported Bicep module for the host pool. The examples below are deliberately smaller, so you can see every moving part.


Minimal Terraform for AVD

This builds a pooled host pool, a rotating registration token, a desktop application group, a workspace and the user assignment. It's written for azurerm 4.x and follows the resources Microsoft uses in its own Terraform tutorial for AVD.

terraform {
  required_providers {
    azurerm = { source = "hashicorp/azurerm", version = "~> 4.0" }
    time    = { source = "hashicorp/time" }
  }
}

provider "azurerm" {
  features {}
  subscription_id = var.subscription_id
}

resource "azurerm_resource_group" "avd" {
  name     = "rg-${var.prefix}"
  location = var.location
}

resource "azurerm_virtual_desktop_host_pool" "pool" {
  name                     = "${var.prefix}-hp"
  resource_group_name      = azurerm_resource_group.avd.name
  location                 = azurerm_resource_group.avd.location
  type                     = "Pooled"
  load_balancer_type       = "BreadthFirst"
  preferred_app_group_type = "Desktop"
  maximum_sessions_allowed = 12
}

# A new token every 7 days, so a stale one never sits in state
resource "time_rotating" "token" {
  rotation_days = 7
}

resource "azurerm_virtual_desktop_host_pool_registration_info" "token" {
  hostpool_id     = azurerm_virtual_desktop_host_pool.pool.id
  expiration_date = time_rotating.token.rotation_rfc3339
}

resource "azurerm_virtual_desktop_application_group" "desktop" {
  name                = "${var.prefix}-dag"
  resource_group_name = azurerm_resource_group.avd.name
  location            = azurerm_resource_group.avd.location
  type                = "Desktop"
  host_pool_id        = azurerm_virtual_desktop_host_pool.pool.id
}

resource "azurerm_virtual_desktop_workspace" "ws" {
  name                = "${var.prefix}-ws"
  resource_group_name = azurerm_resource_group.avd.name
  location            = azurerm_resource_group.avd.location
}

resource "azurerm_virtual_desktop_workspace_application_group_association" "ws_desktop" {
  workspace_id         = azurerm_virtual_desktop_workspace.ws.id
  application_group_id = azurerm_virtual_desktop_application_group.desktop.id
}

resource "azurerm_role_assignment" "users" {
  scope                = azurerm_virtual_desktop_application_group.desktop.id
  role_definition_name = "Desktop Virtualization User"
  principal_id         = var.avd_users_group_object_id
}

Microsoft's tutorial sets the token's expiry from a fixed date variable. Copy it as is and the token has already expired, so every session host fails to register. time_rotating avoids that.


Minimal Bicep for AVD

The same deployment in Bicep. It uses API version 2023-09-05, the version Microsoft asked every deployment to move to in 2024; check the template reference for newer ones.

param location string = resourceGroup().location
param prefix string = 'avd-prod'
param avdUsersGroupObjectId string
param baseTime string = utcNow()

resource hostPool 'Microsoft.DesktopVirtualization/hostPools@2023-09-05' = {
  name: '${prefix}-hp'
  location: location
  properties: {
    hostPoolType: 'Pooled'
    loadBalancerType: 'BreadthFirst'
    preferredAppGroupType: 'Desktop'
    maxSessionLimit: 12
    registrationInfo: {
      expirationTime: dateTimeAdd(baseTime, 'PT24H')
      registrationTokenOperation: 'Update'
    }
  }
}

resource desktopGroup 'Microsoft.DesktopVirtualization/applicationGroups@2023-09-05' = {
  name: '${prefix}-dag'
  location: location
  properties: {
    applicationGroupType: 'Desktop'
    hostPoolArmPath: hostPool.id
  }
}

resource workspace 'Microsoft.DesktopVirtualization/workspaces@2023-09-05' = {
  name: '${prefix}-ws'
  location: location
  properties: {
    applicationGroupReferences: [ desktopGroup.id ]
  }
}

// Desktop Virtualization User
resource userAccess 'Microsoft.Authorization/roleAssignments@2022-04-01' = {
  name: guid(desktopGroup.id, avdUsersGroupObjectId)
  scope: desktopGroup
  properties: {
    roleDefinitionId: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '1d18fff3-a72a-46b5-b4a9-0b38a3cd7e63')
    principalId: avdUsersGroupObjectId
    principalType: 'Group'
  }
}

module sessionHosts 'session-hosts.bicep' = {
  name: 'session-hosts'
  params: {
    hostPoolName: hostPool.name
    registrationToken: first(hostPool.listRegistrationTokens().value).token
  }
}

Two Bicep details catch most people. Since API version 2023-09-05, reading hostPool.properties.registrationInfo.token returns nothing: use listRegistrationTokens() as above. And registrationTokenOperation: 'Update' issues a new token on every deployment, which is what you want, as long as you never print the token as an output. Mark the module's registrationToken parameter @secure().


Session hosts: the part that isn't one resource

The host pool is one resource. A session host is four steps, in order:

  1. The VM, from your image, with no AVD agent baked in. Microsoft says to install the agent after the VM is deployed, so each host registers with its own token.
  2. The directory join. For Active Directory, the JsonADDomainExtension with a join account that has no MFA. For Microsoft Entra ID, the AADLoginForWindows extension, a system-assigned identity on the VM, and Virtual Machine User Login for your users.
  3. The AVD agent, installed by the DSC extension running Microsoft's AddSessionHost configuration with the pool name and the registration token.
  4. Registration. The agent uses the token once; after that the host has its own identity and the token's expiry no longer matters to it.

In Terraform, step 3 looks like this (the settings match Microsoft's session host tutorial):

resource "azurerm_virtual_machine_extension" "avd_agent" {
  count                      = var.host_count
  name                       = "avd-agent"
  virtual_machine_id         = azurerm_windows_virtual_machine.host[count.index].id
  publisher                  = "Microsoft.Powershell"
  type                       = "DSC"
  type_handler_version       = "2.73"
  auto_upgrade_minor_version = true

  settings = jsonencode({
    modulesUrl            = var.avd_dsc_package_url # Microsoft's current Configuration_*.zip
    configurationFunction = "Configuration.ps1\\AddSessionHost"
    properties = {
      HostPoolName = azurerm_virtual_desktop_host_pool.pool.name
    }
  })

  protected_settings = jsonencode({
    properties = {
      registrationInfoToken = azurerm_virtual_desktop_host_pool_registration_info.token.token
    }
  })

  # Don't re-run the extension on every host when the token rotates
  lifecycle {
    ignore_changes = [protected_settings]
  }

  depends_on = [azurerm_virtual_machine_extension.domain_join]
}

Microsoft versions the DSC package (Configuration_<version>.zip) and updates the URL in its samples, so keep it in a variable rather than buried in the module.


Common pitfalls

SymptomCauseFix
Hosts deploy but never appear in the poolThe registration token expired, often a hard-coded date copied from a sampleGenerate the expiry relative to now (time_rotating, dateTimeAdd(utcNow()))
Bicep output or variable for the token is emptyAPI 2023-09-05 and later don't return the token on readUse listRegistrationTokens()
VMExtensionProvisioningError on the domain joinWrong credentials, MFA on the join account, or VNet DNS not pointing at your domain controllersFix the account or DNS; see AVD error codes
Every terraform plan wants to change existing hostsThe rotated token changes the DSC extension's protected settingsignore_changes = [protected_settings] on the extension
Users sign in and see nothingNo role assignment on the application group, or it was given to a distribution groupAssign Desktop Virtualization User to a security group
An image update deletes hosts with users on themChanging the VM's image forces Terraform to replace it, and replacement doesn't drain sessionsAdd new hosts first, drain the old ones, then remove them in a later apply
plan shows changes nobody made in codeSomeone, or another tool, changed the pool in AzureDecide who owns that setting (below)

When an IaC pipeline beats a management platform, and when it doesn't

IaC describes what should exist. It doesn't watch what happens to it, and AVD is a service where most of the work is what happens to it.

JobIaC pipelineManagement platform
Build a pool the same way in a second region or for a second customerBest fit: same code, new variablesWorks, through templates or a wizard
Code review and an audit trail of infrastructure changesBest fit: pull requests and plansAn activity log, but no review before the change
Rebuild after a disasterBest fit, if the code is currentOnly what the platform itself can rebuild
Roll a new image onto hosts with users on themHard: replacement doesn't drain sessions, so it takes several applies or scripts around the pipelineBest fit: add, drain, retire in batches
Scale hosts and session limits through the dayDefines the scaling plan; doesn't make the decisionsBest fit
Help a user who can't connect, or end a stuck sessionNot its jobBest fit
Monitoring, alerts and cost reportingDeploys the workspace and alert rulesBest fit: reads them and acts on them
A one-off fix during an incidentSlow: a change through the pipelineFast, and the next plan shows it

An IaC pipeline on its own is enough when the estate is small, changes rarely, and the people who own the code also take the support calls. A platform starts to pay off when you're rolling images monthly, running more than a couple of pools, supporting users day to day, or managing AVD for several customers.


Running Terraform alongside a management tool

The conflict is always the same: two tools both think they own a setting. Decide once, per setting:

  • Host pool type, load balancing, networking, the workspace and application groups: code. They rarely change, and a change deserves review.
  • Session limit and RDP properties: whichever tool your team edits them in. If a tool tunes the session limit for you, tell Terraform to stop correcting it.
  • Session host VMs: if your management tool adds and replaces hosts, don't keep them in Terraform state, or every replacement shows up as a missing resource. Keep the image, network and pool in code, and the hosts out of it.
resource "azurerm_virtual_desktop_host_pool" "pool" {
  # ...
  lifecycle {
    # Tuned at runtime; don't reset them on every apply
    ignore_changes = [maximum_sessions_allowed, custom_rdp_properties]
  }
}

In Bicep, the equivalent is to leave a runtime-owned property out of the template, so a redeploy doesn't reset it, and to run what-if before each deployment.


Where Atlas AVD fits

Atlas AVD is a management platform for the day-2 side, and it doesn't ask you to give up your code:

  • It works with pools you built in code. Atlas discovers the host pools already in your subscriptions and keeps them in sync with Azure: nothing to rebuild or import.
  • New hosts that match the pool. VM Provisioning adds session hosts from the pool's own settings, fetches the registration token, installs the AVD agent, and fails the job if a host doesn't register in time.
  • Image rollouts that drain first. Re-Image can run a Rolling Replace that builds new hosts first, drains the old ones until their last user signs out, and deletes them in batches you set.
  • Session limits tuned for you. Adaptive Density writes each pool's max session limit in Azure as demand changes, so if you use it, add maximum_sessions_allowed to ignore_changes.
  • Drift you can see. Every 30 minutes Atlas compares each host pool's live configuration, including RDP properties, with its recorded baseline and flags changes made outside Atlas for review, a terraform apply included.
Atlas AVD screenshot. All names, metrics and values are demo data.

That's the real Atlas AVD console in our demo environment; the pools and numbers are sample data.

For the pipeline side, our AVD deployment automation guide covers what a full pipeline includes, and golden image management covers building and versioning the image your code deploys.


FAQ

Can you deploy Azure Virtual Desktop with Terraform?

Yes. The azurerm provider has resources for the host pool, registration token, application group, workspace, the workspace association and scaling plans. Session hosts are ordinary Windows VMs with a domain or Entra join extension and the DSC extension that installs the AVD agent.

Should I use Bicep or Terraform for AVD?

Use the one your team already uses for Azure. Bicep needs no state file and supports new AVD API versions immediately. Terraform suits teams already running it, and can manage Entra groups and other systems in the same run.

Why don't my session hosts register with the host pool?

Usually the registration token had already expired when the host tried to use it, often because a fixed date was copied from a sample. Set the expiry relative to the deployment time. In Bicep on API 2023-09-05 or later, read the token with listRegistrationTokens(), because the host pool no longer returns it on read.

Is there an official Azure Verified Module for AVD?

Yes. Azure Verified Modules publishes AVD modules, including a Bicep module for the host pool, and Microsoft's AVD landing zone accelerator has full reference deployments in Bicep and Terraform.

How do I update the image without disconnecting users?

Don't change the image on existing VMs in code: Terraform replaces them without draining. Deploy new hosts from the new image, set the old ones to drain mode, and remove them once their sessions end. A management platform can run that sequence for you.

Do I still need a management tool if all my AVD is in code?

Not to build it. You need something for daily operations: draining hosts for image updates, scaling, user support, monitoring and cost. Small, stable estates can do that with scripts and the Azure portal. Larger ones, or MSPs with many customers, usually add a platform and keep the code for the infrastructure.

Last updated 24 November 2026. Microsoft details are drawn from Microsoft Learn as of November 2026: Configure Azure Virtual Desktop using Terraform, Configure Azure Virtual Desktop session hosts using Terraform, the host pool template reference, Built-in Azure RBAC roles for Azure Virtual Desktop and Microsoft's notice on moving to the 2023-09-05 Desktop Virtualization API.

Related Resources

Blog

Azure Virtual Desktop Error Codes: The Complete List, With Fixes

A reference for Azure Virtual Desktop error codes, organized by where they come from: ARM deployment errors such as VMExtensionProvisioningError, domain join and registration failures, agent events 3277, 3703 and 3019, session host health checks, WVDErrors, Entra sign-in errors and client messages, each with its cause and fix and a link to the full guide.

Read more
Blog

Azure Virtual Desktop PowerShell Cheat Sheet: Az.DesktopVirtualization Commands You Can Copy

Copyable Az.DesktopVirtualization commands for the AVD jobs you do every week: host pools, session hosts, drain mode, user sessions (message, disconnect, log off), registration tokens, application groups and scaling plans, plus the naming and parameter traps that break scripts.

Read more
Blog

Azure Virtual Desktop ROI: Thin Clients and BYOD vs a Laptop Refresh at 2026 RAM Prices

PC memory contract prices more than doubled in early 2026, and a laptop refresh buys 16 GB of it per user at the peak. A worked 3-year example for 100 users compares that refresh with Azure Virtual Desktop on thin clients and on the devices people already have, shows every input, and says where the ROI stops working.

Read more
Blog

Why Aren't You Using Ephemeral OS Disks for Your AVD Session Hosts Yet?

Pooled Azure Virtual Desktop hosts that run most of the day are a natural fit for ephemeral OS disks: Windows runs from the VM's local storage, the disk itself isn't billed, and nothing on the host outlives a reimage. The five reasons teams give for not switching, which three have stopped applying, and the two that still need a decision.

Read more

Get the AVD health checklist

The checks that catch slow sign-ins, temporary profiles and surprise Azure bills, across session hosts, FSLogix, golden images and cost. Free, straight to your inbox.

No spam. Unsubscribe anytime.

Ready to put this into practice?

Atlas AVD automates the strategies in this article - cost optimization, scaling, governance, and more.

Start free, no credit card

Free forever for 1 tenant & 1 host pool on the Community plan, or 30 days of every feature.

Try the live demo, no signup

The minimal infrastructure as code for Azure Virtual Desktop in Bicep and in Terraform: host pool, registration token, desktop application group, workspace, user assignment and session hosts, the pitfalls that stop hosts registering, and when an IaC pipeline beats a management platform and when it doesn't.

By David Smith, Founder and CEO, Atlas AVD, , updated