In this chapter, we take a look at automating Azure Virtual Desktop by taking repeated processes and automating them on a schedule. We will then dive into the automation management of host pools, session hosts, and user sessions using an automation account.
In this chapter, we take a look at the following topics:
In this section, we look at creating an automation account for Azure Virtual Desktop. An automation account is used to create runbooks that contain scripts that can automate processes to help you manage your Azure Virtual Desktop environment. Runbooks are extremely useful for automating repetitive tasks and batch processing, which can be quite time-consuming when carrying out such tasks manually.
Let's get started with first creating an automation account:
There you have it – we have created an Azure automation account ready for use with Azure Virtual Desktop. The next section looks at some of the automation tasks you can use to simplify Azure Virtual Desktop management.
This section looks at using the Azure command-line interface and Azure automation accounts to run repeat tasks and simplify tasks such as logging off multiple users in a batch.
This section takes you through creating an Azure automation runbook, configuring the runbook, testing, and configuring a runbook schedule.
This section shows you how to create a simple host pool log-off script using an automation account.
You will need a run as account set up for this example.
You can configure a run as account within the automation account in the Account Settings | Run as accounts | Create Run As account section:
Once you have set up the run as account, you can then progress to preparing the automation account with the correct PowerShell modules, which can be imported using the module gallery.
The following modules need to be imported:
The following screenshot shows the automation account's module gallery, where you would add PowerShell modules for use within runbooks:
Once you have begun importing the modules, you will see the status is Importing. Once importing has finished, you should see the modules shown as available:
The next part of this process is to create a PowerShell runbook within the Azure automation account that we have just created.
We'll now take a look at creating a PowerShell runbook within the automation account.
To create a runbook, navigate to the automation account. Under Process Automation, click Runbooks; once on the Runbooks page, click on Create a runbook:
You will then see the Create a runbook blade appear. Enter a name for the runbook and select the type – in this case, it's a PowerShell runbook. Provide a description:
Once the new runbook is created, it will open the runbook page ready for you to start configuring:
Now that we have created a runbook, we can proceed with configuring it with the required script. In this example, we will be creating a host pool log-off runbook to simplify the logging off of multiple users spread across several session hosts within a host pool.
Let's take now take a look at adding the PowerShell script to the runbook.
The first thing we need to do is click Edit within the runbook page, as shown in the following screenshot:
You should now see the runbook scripting interface; this is where you need to enter the PowerShell cmdlets:
Before entering the scripting and testing, I want to briefly run through the host pool log-off example. This is broken down into multiple sections so that I can discuss the key parts of the script.
The first part of the script is the header, detailing information about the script and any imports you may need for the script:
# Mastering Azure Virtual Desktop Log Off User example
import-module az.DesktopVirtualization
import-module AzureAD
The next part of the script is the authentication piece. This is needed to ensure the runbook can communicate with the tenant. In this example, we are using the Azure Run as connection to authenticate:
# Azure Runbook Auth using RunAsConnection
# Get the connection "AzureRunAsConnection"
$connectionName = "AzureRunAsConnection"
$servicePrincipalConnection = Get-AutomationConnection -Name $connectionName
$logonAttempt = 0
$logonResult = $False
while(!($connectionResult) -And ($logonAttempt -le 10))
{
$LogonAttempt++
#Logging in to Azure...
$connectionResult = Connect-AzAccount '
-ServicePrincipal '
-Tenant $servicePrincipalConnection.TenantId '
-ApplicationId $servicePrincipalConnection.ApplicationId '
-CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
Start-Sleep -Seconds 30
}
Now that we have authenticated with Azure, the next part of the script will call the log-off function. As you will note, the only area you need to specify is the resource group name. Everything else is taken care of for you. This part essentially reads the resource group for Azure Virtual Desktop host pools. The script then counts the user sessions within the host pool and runs Remove-AzWvdUserSession for each session. This automates the log-off process for host pools, which in turn simplifies the IT admin's effort to carry out maintenance and so on:
# Start AVD Task...
$ResourceGroupName = "avd01-avd" # <<<< enter resource group
$ExistingHostPool = Get-AzResource -ResourceGroupName $ResourceGroupName | Where-Object ResourceType -eq Microsoft.DesktopVirtualization/hostpools
if (($ExistingHostPool).count -gt "0") {
# Process to Log off connected Users
foreach($Hostpool in $ExistingHostPool){
$AVDUserSessions = Get-AzWvdUserSession -HostPoolName $HostPool.Name -ResourceGroupName $ResourceGroupName
$NumberofAVDSessions = ($AVDUserSessions).count # Counts sessions
if ($NumberofAVDSessions -gt "0") {
try {
Write-Host "There are a total of $NumberofAVDSessions logged on, these user sessions now will be logged off" # Admin message
foreach ($AVDUserSession in $AVDUserSessions){
$InputString = $AVDUserSession.Name
$AVDUserArray = $InputString.Split("/")
$AVDUserArray[0]
$AVDUserArray[1]
$AVDUserArray[2]
Remove-AzWvdUserSession -HostPoolName $HostPool.Name -ResourceGroupName $ResourceGroupName -SessionHostName $AVDUserArray[1] -Id $AVDUserArray[2]
}clear # clears PowerShell output
}
catch {
}
}
}
}
You can download the full script here: https://github.com/PacktPublishing/Remote-Productivity-with-Windows-Virtual-Desktop/blob/main/B17392_07/logoff%20AVD%20Users%20Batch.ps1
Now that we have run through the host pool log-off script structure, we will proceed with configuring the runbook and publishing it:
Once you have copied the script into the PowerShell runbook, you can proceed with testing by clicking Test pane, as shown in the following screenshot:
In the next section, we take a look at testing the script before publishing.
This section runs through the basics of using the test pane to test the script we created for logging off Azure Virtual Desktop users within a host pool.
To test the script, all you need to do is click the Start icon as shown in Figure 17.15:
In the next section, we look at creating a schedule and assigning the created runbook to it.
Follow these steps to create a schedule:
In this section, we looked at configuring an Azure automation runbook. First, we covered the setup of a run as account and the importing of required PowerShell modules for an Azure Virtual Desktop PowerShell script to run. We then created the runbook, added the PowerShell script to the runbook, and tested it. We then finished the section by creating an automated schedule for the runbook to run at a specific time.
In the next section, we look at implementing autoscaling in Azure Virtual Desktop using an automation account.
In this section, we look at how to configure autoscaling for Azure Virtual Desktop.
The Azure Virtual Desktop autoscale tool optimizes cost and capacity for your Virtual Desktop environment based on time and resource requirements. The tool requires the following Azure components:
We will take a look at these components in more detail shortly.
The autoscale tool essentially allows you to scale up and scale down resources based on the requirement.
Here are the key features of the autoscale tool:
The tool works based on the following scheduling parameters:
The scaling tool works by running a number of jobs to check the current number of user sessions against the total number of VMs running. First, this information is collected, and then a calculation is completed using the parameter SessionThresholdPerCPU. Finally, suppose the current resources cannot support the existing active user sessions. In that case, the autoscale tool will start a job to start additional session host VMs within the host pool.
Important Note
It is important to note that the SessionthresholdPerCPU parameter only determines when new VMs need to be started. It does not restrict the number of user sessions. The restriction of sessions is completed using the MaxSessionLimit parameter.
The out-of-hours usage time, also known as an off-peak job, runs to check how many session host VMs need to be shut down based on the MinimumNumberOfRDSH parameter. Suppose you set the LimitSecondsToForceLogOffUser parameter to a number greater than zero. In that case, the job will enable drain mode on the session host VMs to prevent new sessions from connecting to the hosts. The job to shut down session hosts sends a message to the users notifying them to save their work. However, once the LimitSecondsToForceLogOffUser parameter is reached, all user sessions will be logged off. Once all users have been logged out, the job will then start to shut down the VM. If you leave the LimitSecondsToForceLogOffUser parameter as zero, then the job will take no action to force users off a session host; if no users are on the session host, it will shut down the VM.
Important Note
If a session host is already in drain mode, set manually, the job to shut down will ignore the session host in question. Instead, the job will treat the session host as unavailable, making the job start additional VMs to handle the user session load.
The job considers the host pool's MaxSessionLimit to calculate if the active number of user sessions is more than 90% of the maximum capacity. If it is, the job will start additional VMs (session hosts).
Here are the autoscale tool's limitations:
Before we can get started with setting up the autoscaling tool, you need to make sure you have the following ready:
In this section, we take a look at deploying an Azure Virtual Desktop autoscale automation account:
New-Item -ItemType Directory -Path "C:Temp" -Force
Set-Location -Path "C:Temp"
$Uri = "https://raw.githubusercontent.com/Azure/RDS-Templates/master/wvd-templates/wvd-scaling-script/CreateOrUpdateAzAutoAccount.ps1"
# Download the script
Invoke-WebRequest -Uri $Uri -OutFile ".CreateOrUpdateAzAutoAccount.ps1"
You can download the configuration script here: https://github.com/PacktPublishing/Remote-Productivity-with-Windows-Virtual-Desktop/blob/main/B17392_07/Automation%20account%20config%20script.ps1.
The following table shows the different parameters you will need to configure for the configuration script:
The following screenshot shows the finished output from PowerShell:
Once the script has finished and your new automation account has been created, you will see the WVDAutoScaleRunbook runbook within the automation account.
Important Note
Make sure you configure the run as account as shown in the Setting up a run as account section before proceeding to the next section.
Now that we have the required automation account and runbook deployed, we can move on to the final stage of deployment by creating an Azure Logic Apps account and setting the schedule.
We'll now look at deploying an Azure logic app. Like in the previous section, the logic app is deployed using PowerShell, which first downloads the script, and then we use a configuration script for the schedule.
Let's get started:
New-Item -ItemType Directory -Path "C:Temp" -Force
Set-Location -Path "C:Temp"
$Uri = "https://raw.githubusercontent.com/Azure/RDS-Templates/master/wvd-templates/wvd-scaling-script/CreateOrUpdateAzLogicApp.ps1"
# Download the script
Invoke-WebRequest -Uri $Uri -OutFile ".CreateOrUpdateAzLogicApp.ps1"
The following screenshot shows the preceding script run, which downloads the Createorupdateazlogicapp.ps1 script:
Now you have downloaded the script, you will need to configure the configuration script to deploy the logic app. When running the configuration script, you will be asked a series of questions to configure the logic app. Please note you can skip some of the questions as shown in the following table, which has a default setting. You can download the logic app script here: https://github.com/PacktPublishing/Remote-Productivity-with-Windows-Virtual-Desktop/blob/main/B17392_07/Autoscale_logicapp_config.ps1.
Important Note
Make sure you populate all the fields apart from the Log Analytics Workspace ID, as this is optional.
The following table shows the parameters you need to configure to deploy the Azure logic app:
Once the deployment has finished, you should now see the Azure logic app appear in the resource group:
Once complete, you should see the following within the Jobs section of the automation account:
The following screenshot shows the jobs under Process Automation:
We have now configured autoscaling for Azure Virtual Desktop. Microsoft has announced a new feature to simplify this at the time of writing, which is in public preview. Scaling plans simplify the configuration and management of autoscale for Azure Virtual Desktop.
We will now progress to the final section of this chapter, where we deploy scaling plans (public preview) for Azure Virtual Desktop.
There are two key components used for the autoscaling tool – the automation account that contains the PowerShell runbook and the Azure logic app, which holds the configuration for the autoscaling to work.
To make changes to the autoscaling tool, open the configured logic app. For example, under the Development Tools section, you would select Logic app designer and expand the HTTP section. Within the HTTP section, you can edit the configuration held in the body section.
To stop the autoscaling jobs from running, you would simply navigate to the Azure logic app and click Disable, located in the logic app page's main menu bar, as shown in the following screenshot:
Please note at the time of writing, autoscale within the Azure portal is in public preview.
The built-in autoscale feature with Azure Virtual Desktop simplifies automating scale based on time and session limits per session host. This preview feature is expected to supersede the current autoscale feature, which is deployed using PowerShell. However, it is important to note the scaling plans do not have the same flexibility as the PowerShell version, which can be customized with additional algorithms, settings, and other customisations.
Important Note
Ephemeral disks are not supported when using the autoscale feature for Azure Virtual Desktop.
Before we can start configuring a scaling plan, we first need to configure the required custom role in IAM. To simplify this, I have created a pre-configured JSON file with the correct permissions for the custom role:
Once complete, you should see the custom role with the Windows Virtual Desktop app (service) added:
Important Note
At the time of writing, the name Windows Virtual Desktop has not changed in some parts of Microsoft Azure. However, this is subject to change, and you should look out for the new Azure Virtual Desktop name.
In this section, we looked at creating a custom role for scaling plans for Azure Virtual Desktop. We can now proceed with looking at creating our first scaling plan.
Before creating a scaling plan, you first need to ensure you have an existing pooled host pool. All your host pools must have a configured maxSessionLimit parameter.
Important Note
You can update the MaxSessionLimit parameter using the PowerShell cmdlet New-AZWvdHostPool or Update-AZWvdHostPool.
Getting started:
We'll now move on to look at the configuration of a schedule within a scaling plan.
Schedules are essentially the configuration settings for autoscale. This includes the ramp-up and ramp-down modes, which will activate based on schedules throughout the day.
The following table details the different terms and meanings:
To configure or change a schedule, follow these steps:
Important Note
When applying load balancing preferences within a scale plan schedule, you will override the original host pool load balancing setting.
For Ramp-down, you will see similar values to the Ramp-up section. It is important to note that in this instance, it will be for reduced host pool usage, also known as drop-offs. The Ramp-down section includes the Force logoff users, Delay time before logging out users and shutting down VMs (min), and the ability to send a message to the user before they are logged off:
Off-peak hours work in a similar way to peak hours. The difference is that off-peak hours gradually reduce the number of session hosts based on the user sessions on each session host:
Now that we have configured the schedule, we can now assign host pools to the scaling plan.
The following steps look at the steps to assign the host pool and complete the creation of the scaling plan:
This concludes the setup process for creating a scaling plan in Azure Virtual Desktop.
There you have it – in this section, we looked at the in-preview Azure portal-based autoscale feature where you can configure scaling plans that meet your specific requirements.
For the latest updates and information on the autoscale tool, see the following Microsoft documentation link: https://docs.microsoft.com/azure/virtual-desktop/autoscale-scaling-plan.
In this chapter, we started by configuring an Azure automation account and then looked at automating Azure Virtual Desktop tasks such as logging multiple sessions of session hosts within a host pool. We then moved on to take a look at the autoscaling feature of Azure Virtual Desktop, which uses a series of PowerShell scripts for deployment. Then we finished off the chapter by looking at a preview feature (at the time of writing) called scaling plans. Finally, we ran through the setup of a scaling plan, configuring a schedule and assigning host pools to a scaling plan.
In the next chapter, we look at the topic of monitoring and managing the performance and health of an Azure Virtual Desktop environment.