Deallocate VM on user logoff

%3CLINGO-SUB%20id%3D%22lingo-sub-2280211%22%20slang%3D%22en-US%22%3EDeallocate%20VM%20on%20user%20logoff%3C%2FLINGO-SUB%3E%3CLINGO-BODY%20id%3D%22lingo-body-2280211%22%20slang%3D%22en-US%22%3E%3CP%3ERecently%20we've%20announced%20the%20public%20preview%20of%20%3CA%20href%3D%22https%3A%2F%2Fdocs.microsoft.com%2Fen-us%2Fazure%2Fvirtual-desktop%2Fstart-virtual-machine-connect%22%20target%3D%22_self%22%20rel%3D%22noopener%20noreferrer%22%3Estart%20VM%20on%20connect%3C%2FA%3E%26nbsp%3Bwhich%20will%20allow%20your%20deallocated%20virtual%20machines%20getting%20started%20automatically%20when%20the%20assigned%20user%20tries%20to%20connect.%20Let%20us%20have%20a%20look%20how%20we%20can%20further%20optimize%20our%20cost%20by%20deallocating%20the%20VM%20when%20it%20is%20not%20used%20anymore.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3ELet's%20first%20have%20a%20high%20level%20view%20on%20the%20needed%20steps%3A%3C%2FP%3E%0A%3CUL%3E%0A%3CLI%3ECreate%20a%20custom%20role%20to%20deallocate%20a%20virtual%20machine%3C%2FLI%3E%0A%3CLI%3ECreate%20a%20managed%20identity%20for%20your%20virtual%20machines%3C%2FLI%3E%0A%3CLI%3EAllow%20each%20virtual%20machine%20to%20deallocate%20itself%20via%20a%20role%20assignment%3C%2FLI%3E%0A%3CLI%3Eimplement%20logoff%20script%20and%20policies%20around%20idle%2Fdisconnected%20sessions%3C%2FLI%3E%0A%3C%2FUL%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3ESo%20let's%20start%20by%20creating%20our%20custom%20role%3A%3C%2FP%3E%0A%3COL%3E%0A%3CLI%3E%3CP%3EOpen%20the%20Azure%20portal%2C%20go%20to%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E%3CSTRONG%3ESubscriptions%3C%2FSTRONG%3E%26nbsp%3Band%20select%20the%20appropriate%20subscription%3C%2FP%3E%0A%3C%2FLI%3E%0A%3CLI%3E%3CP%3EGo%20to%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E%3CSTRONG%3EAccess%20control%20(IAM)%3C%2FSTRONG%3E%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3Eand%20select%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E%3CSTRONG%3EAdd%20a%20custom%20role%3C%2FSTRONG%3E.%3CBR%20%2F%3E%3CSPAN%20class%3D%22lia-inline-image-display-wrapper%20lia-image-align-left%22%20image-alt%3D%22add-custom-role.png%22%20style%3D%22width%3A%20400px%3B%22%3E%3CIMG%20src%3D%22https%3A%2F%2Ftechcommunity.microsoft.com%2Ft5%2Fimage%2Fserverpage%2Fimage-id%2F273038iB1CA9430E057FC43%2Fimage-size%2Fmedium%3Fv%3Dv2%26amp%3Bpx%3D400%22%20role%3D%22button%22%20title%3D%22add-custom-role.png%22%20alt%3D%22add-custom-role.png%22%20%2F%3E%3C%2FSPAN%3E%3C%2FP%3E%0A%3C%2FLI%3E%0A%3CLI%3E%3CP%3ENext%2C%20name%20the%20custom%20role%20and%20add%20a%20description.%20In%20this%20example%20I'll%20call%20it%26nbsp%3B%22Deallocate%20VM%20on%20logoff%22%3C%2FP%3E%0A%3C%2FLI%3E%0A%3CLI%3E%3CP%3EOn%20the%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E%3CSTRONG%3EPermissions%3C%2FSTRONG%3E%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3Etab%2C%20add%20the%20following%20permission%20to%20the%20subscription%20you're%20assigning%20the%20role%20to%3A%3C%2FP%3E%0A%3CUL%3E%0A%3CLI%3EMicrosoft.Compute%2FvirtualMachines%2Fdeallocate%2Faction%3C%2FLI%3E%0A%3C%2FUL%3E%0A%3C%2FLI%3E%0A%3CLI%3E%3CP%3EWhen%20you're%20finished%2C%20select%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E%3CSTRONG%3EOk%3C%2FSTRONG%3E.%3C%2FP%3E%0A%3C%2FLI%3E%0A%3C%2FOL%3E%0A%3CP%3EIf%20you%20prefer%20a%20JSON%20definition%2C%20please%20use%20the%20following%20template%3A%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CPRE%20class%3D%22lia-code-sample%20language-json%22%3E%3CCODE%3E%7B%0A%20%20%20%20%22properties%22%3A%20%7B%0A%20%20%20%20%20%20%20%20%22roleName%22%3A%20%22Deallocate%20VM%20on%20logoff%22%2C%0A%20%20%20%20%20%20%20%20%22description%22%3A%20%22This%20custom%20role%20will%20allow%20your%20virtual%20machines%20to%20be%20deallocated%20when%20the%20user%20logs%20off.%22%2C%0A%20%20%20%20%20%20%20%20%22assignableScopes%22%3A%20%5B%0A%20%20%20%20%20%20%20%20%20%20%20%20%22%2Fsubscriptions%2F%26lt%3B%26lt%3B%3CSUBSCRIPTIONID%3E%26gt%3B%26gt%3B%22%0A%20%20%20%20%20%20%20%20%5D%2C%0A%20%20%20%20%20%20%20%20%22permissions%22%3A%20%5B%0A%20%20%20%20%20%20%20%20%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22actions%22%3A%20%5B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22Microsoft.Compute%2FvirtualMachines%2Fdeallocate%2Faction%22%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%5D%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22notActions%22%3A%20%5B%5D%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22dataActions%22%3A%20%5B%5D%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22notDataActions%22%3A%20%5B%5D%0A%20%20%20%20%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%20%20%5D%0A%20%20%20%20%7D%0A%7D%3C%2FSUBSCRIPTIONID%3E%3C%2FCODE%3E%3C%2FPRE%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EAfter%20we've%20created%20our%20custom%20role%2C%20we'll%20need%20to%20create%20a%20managed%20identity%20for%20our%20virtual%20machines.%20By%20this%20managed%20identities%20we%20don't%20need%20to%20store%20any%20credentials%20locally%20on%20the%20virtual%20machine%20or%20in%20an%20Azure%20KeyVault%20and%20can%20assign%20each%20virtual%20machine%20granular%20permission%20to%20shutdown%20only%20itself.%3C%2FP%3E%0A%3CP%3EAs%20this%20can%20be%20a%20bigger%20task%2C%20depending%20on%20the%20number%20of%20virtual%20machines%20you%20have%20in%20your%20personal%20host%20pools%2C%20I've%20prepared%20a%20script%20that%20will%20utilize%20the%20Azure%20PowerShell%20modules%20to%20assign%20that%20fine-grained%20permissions%2C%20so%20you%20may%20need%20to%20install%20those%20modules%20first%3A%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CPRE%20class%3D%22lia-code-sample%20language-powershell%22%3E%3CCODE%3EInstall-Module%20-Name%20Az.Account%2CAz.Compute%2CAz.DesktopVirtualization%2CAz.Resources%3C%2FCODE%3E%3C%2FPRE%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EThe%20script%20itself%20takes%20the%20host%20pool%20name%2C%20associated%20resource%20group%20and%20the%20role%20definition%20name%20selected%20above%20as%20parameters.%20It%20will%20then%20iterate%20through%20all%20virtual%20machines%20assigned%20to%20the%20specified%20host%20pool%2C%20create%20a%20managed%20identity%20when%20not%20already%20present%20and%20create%20a%20role%20assignment%20limited%20to%20the%20virtual%20machine%20itself%3A%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CPRE%20class%3D%22lia-code-sample%20language-powershell%22%3E%3CCODE%3E%24hostPoolName%20%3D%20%22%26lt%3B%26lt%3B%3CHOSTPOOLNAME%3E%26gt%3B%26gt%3B%22%0A%24resourceGroupName%20%3D%20%22%26lt%3B%26lt%3B%3CRESOURCEGROUPNAME%3E%26gt%3B%26gt%3B%22%0A%24roleDefinitionName%20%3D%20%22%26lt%3B%26lt%3B%3CROLEDEFINITIONNAME%3E%26gt%3B%26gt%3B%22%0A%0AConnect-AzAccount%0A%24sessionHosts%20%3D%20Get-AzWvdSessionHost%20-HostPoolName%20%24hostPoolName%20-ResourceGroupName%20%24resourceGroupName%0Aforeach%20(%24sessionHost%20in%20%24sessionHosts)%20%7B%0A%20%26lt%3B%23%20get%20virtual%20machine%20by%20session%20host%20reference%20%23%26gt%3B%0A%20%24resource%20%3D%20%20Get-AzResource%20-ResourceId%20%24sessionHost.ResourceId%0A%20%24vm%20%3D%20Get-AzVM%20-ResourceGroupName%20%24resource.ResourceGroupName%20-Name%20%24resource.Name%0A%20%0A%20%26lt%3B%23%20create%20system-assigned%20managed%20identiy%20unless%20it%20already%20exists%20%23%26gt%3B%0A%20%24managedIdentity%20%3D%20(%24vm.Identity%20%7C%20where%20Type%20-eq%20%22SystemAssigned%22).PrincipalId%0A%20if%20(%24managedIdentity%20-eq%20%24Null)%20%7B%0A%20%20Update-AzVM%20-ResourceGroupName%20%24vm.ResourceGroupName%20-VM%20%24vm%20-IdentityType%20SystemAssigned%0A%20%20%24managedIdentity%20%3D%20((Get-AzVM%20-ResourceGroupName%20%24vm.ResourceGroupName%20-VMName%20%24vm.Name).Identity%20%7C%20where%20Type%20-eq%20%22SystemAssigned%22).PrincipalId%0A%20%7D%0A%20%0A%20%26lt%3B%23%20create%20role-assignment%20unless%20it%20already%20exists%20%23%26gt%3B%0A%20if%20((Get-AzRoleAssignment%20-RoleDefinitionName%20%24roleDefinitionName%20-ObjectId%20%24managedIdentity)%20-eq%20%24Null)%20%7B%0A%20%20New-AzRoleAssignment%20-ObjectId%20%24managedIdentity%20-RoleDefinitionName%20%24roleDefinitionName%20-Scope%20%24vm.Id%0A%20%7D%0A%7D%3C%2FROLEDEFINITIONNAME%3E%3C%2FRESOURCEGROUPNAME%3E%3C%2FHOSTPOOLNAME%3E%3C%2FCODE%3E%3C%2FPRE%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3ENext%20we'll%20configure%20our%20session%20host%20to%20disconnect%20idle%20sessions%20and%20logoff%20disconnected%20sessions%20after%20a%20certain%20period%20of%20time%3A%3C%2FP%3E%0A%3COL%3E%0A%3CLI%3E%3CP%3EConnect%20remotely%20to%20the%20VM%20that%20you%20want%20to%20set%20the%20policy%20for.%3C%2FP%3E%0A%3C%2FLI%3E%0A%3CLI%3E%3CP%3EOpen%20the%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E%3CSTRONG%3EGroup%20Policy%20Editor%3C%2FSTRONG%3E%2C%20then%20go%20to%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E%3CSTRONG%3ELocal%20Computer%20Policy%3C%2FSTRONG%3E%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E%26gt%3B%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E%3CSTRONG%3EComputer%20Configuration%3C%2FSTRONG%3E%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E%26gt%3B%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E%3CSTRONG%3EAdministrative%20Templates%3C%2FSTRONG%3E%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E%26gt%3B%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E%3CSTRONG%3EWindows%20Components%3C%2FSTRONG%3E%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E%26gt%3B%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E%3CSTRONG%3ERemote%20Desktop%20Services%3C%2FSTRONG%3E%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E%26gt%3B%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E%3CSTRONG%3ERemote%20Desktop%20Session%20Host%3C%2FSTRONG%3E%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E%26gt%3B%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E%3CSTRONG%3ESession%20Time%20Limits%3C%2FSTRONG%3E.%3C%2FP%3E%0A%3C%2FLI%3E%0A%3CLI%3E%3CP%3EFind%20the%20policy%20that%20says%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E%3CSTRONG%3ESet%20time%20limit%20for%20disconnected%20sessions%3C%2FSTRONG%3E%2C%20then%20change%20its%20value%20to%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E%3CSTRONG%3EEnabled%3C%2FSTRONG%3E.%3C%2FP%3E%0A%3C%2FLI%3E%0A%3CLI%3E%3CP%3EAfter%20you've%20enabled%20the%20policy%2C%20select%3CSPAN%3E%26nbsp%3Byour%20preferred%20time%20limit%20at%26nbsp%3B%3C%2FSPAN%3E%3CSTRONG%3EEnd%20a%20disconnected%20session%3C%2FSTRONG%3E.%3C%2FP%3E%0A%3C%2FLI%3E%0A%3CLI%3EFind%20the%20policy%20that%20says%20%3CSTRONG%3ESet%20time%20limit%20for%20active%20but%20idle%20Remote%20Desktop%20Services%20sessions%3C%2FSTRONG%3E%2C%20then%20change%20its%20value%20to%20%3CSTRONG%3EEnabled%3C%2FSTRONG%3E.%3C%2FLI%3E%0A%3CLI%3EAfter%20you've%20enabled%20the%20policy%2C%20select%20your%20preferred%20time%20limit%20at%20%3CSTRONG%3EIdle%20session%20limit%3C%2FSTRONG%3E.%3C%2FLI%3E%0A%3C%2FOL%3E%0A%3CP%3EThe%20above%20settings%20also%20ensure%20that%20an%20user%20will%20get%20a%20warning%20message%20two%20minutes%20before%20reaching%20the%20specified%20time%20limit%20so%20he%20can%20press%20a%20key%20or%20move%20the%20mouse%20to%20prevent%20getting%20disconnected.%3C%2FP%3E%0A%3CP%3E%3CSPAN%20class%3D%22lia-inline-image-display-wrapper%20lia-image-align-inline%22%20image-alt%3D%22idle-timer-expired.png%22%20style%3D%22width%3A%20400px%3B%22%3E%3CIMG%20src%3D%22https%3A%2F%2Ftechcommunity.microsoft.com%2Ft5%2Fimage%2Fserverpage%2Fimage-id%2F273040i8599D9899D68DEB7%2Fimage-size%2Fmedium%3Fv%3Dv2%26amp%3Bpx%3D400%22%20role%3D%22button%22%20title%3D%22idle-timer-expired.png%22%20alt%3D%22idle-timer-expired.png%22%20%2F%3E%3C%2FSPAN%3E%3C%2FP%3E%0A%3CP%3EIn%20the%20last%20step%20we'll%20create%20the%20PowerShell%20script%20initiating%20the%20deallocation%20and%20configure%20it%20as%20a%20logoff%20script.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EThe%20PowerShell%20script%20will%20query%20the%20details%20of%20your%20virtual%20machine%20using%20the%20Azure%20instance%20metadata%2C%20connect%20to%20Azure%20using%20the%20created%20managed%20identity%20and%20initiate%20the%20actual%20deallocation%20via%20REST%20API%3A%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CPRE%20class%3D%22lia-code-sample%20language-powershell%22%3E%3CCODE%3E%24metadata%20%3D%20Invoke-RestMethod%20-Headers%20%40%7B%22Metadata%22%3D%22true%22%7D%20-Method%20GET%20-Proxy%20%24Null%20-Uri%20%22http%3A%2F%2F169.254.169.254%2Fmetadata%2Finstance%3Fapi-version%3D2021-01-01%22%0A%24authorizationToken%20%3D%20Invoke-RestMethod%20-Headers%20%40%7B%22Metadata%22%3D%22true%22%7D%20-Method%20Get%20-Proxy%20%24Null%20-Uri%20%22http%3A%2F%2F169.254.169.254%2Fmetadata%2Fidentity%2Foauth2%2Ftoken%3Fapi-version%3D2021-01-01%26amp%3Bresource%3Dhttps%3A%2F%2Fmanagement.azure.com%2F%22%0A%0A%24subscriptionId%20%3D%20%24metadata.compute.subscriptionId%0A%24resourceGroupName%20%3D%20%24metadata.compute.resourceGroupName%0A%24vmName%20%3D%20%24metadata.compute.name%0A%24accessToken%20%3D%20%24authorizationToken.access_token%0A%0AInvoke-WebRequest%20-UseBasicParsing%20-Headers%20%40%7B%20Authorization%20%3D%22Bearer%20%24accessToken%22%7D%20-Method%20POST%20-Proxy%20%24Null%20-Uri%20https%3A%2F%2Fmanagement.azure.com%2Fsubscriptions%2F%24subscriptionId%2FresourceGroups%2F%24resourceGroupName%2Fproviders%2FMicrosoft.Compute%2FvirtualMachines%2F%24vmName%2Fdeallocate%3Fapi-version%3D2021-03-01%20-ContentType%20%22application%2Fjson%22%3C%2FCODE%3E%3C%2FPRE%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3ETo%20have%20that%20script%20executed%20upon%20logoff%2C%20we%20need%20to%20configure%20it%3A%3C%2FP%3E%0A%3COL%3E%0A%3CLI%3E%3CP%3EConnect%20remotely%20to%20the%20VM%20that%20you%20want%20to%20set%20the%20policy%20for.%3C%2FP%3E%0A%3C%2FLI%3E%0A%3CLI%3E%3CP%3EOpen%20the%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E%3CSTRONG%3EGroup%20Policy%20Editor%3C%2FSTRONG%3E%2C%20then%20go%20to%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E%3CSTRONG%3ELocal%20Computer%20Policy%3C%2FSTRONG%3E%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E%26gt%3B%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E%3CSTRONG%3EUser%20Configuration%3C%2FSTRONG%3E%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E%26gt%3B%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E%3CSTRONG%3EWindows%20Settings%3C%2FSTRONG%3E%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E%26gt%3B%3CSPAN%3E%26nbsp%3B%3C%2FSPAN%3E%3CSTRONG%3EScripts%20(Logon%2FLogoff)%3C%2FSTRONG%3E.%3C%2FP%3E%0A%3C%2FLI%3E%0A%3CLI%3E%3CP%3EFind%20the%20item%20that%20says%3CSPAN%3E%26nbsp%3B%3CSTRONG%3ELogoff%3C%2FSTRONG%3E%3C%2FSPAN%3E.%3C%2FP%3E%0A%3C%2FLI%3E%0A%3CLI%3E%3CP%3E%3CSPAN%3ESpecify%20the%20script%20you've%20created%20on%20the%26nbsp%3B%3C%2FSPAN%3E%3CSTRONG%3EPowerShell%20Scripts%3C%2FSTRONG%3E%20tab.%3C%2FP%3E%0A%3C%2FLI%3E%0A%3C%2FOL%3E%0A%3CP%3E%3CSPAN%20class%3D%22lia-inline-image-display-wrapper%20lia-image-align-inline%22%20image-alt%3D%22logoff-script.png%22%20style%3D%22width%3A%20351px%3B%22%3E%3CIMG%20src%3D%22https%3A%2F%2Ftechcommunity.microsoft.com%2Ft5%2Fimage%2Fserverpage%2Fimage-id%2F273043iC99C9D3FCD14C332%2Fimage-size%2Fmedium%3Fv%3Dv2%26amp%3Bpx%3D400%22%20role%3D%22button%22%20title%3D%22logoff-script.png%22%20alt%3D%22Place%22%20%2F%3E%3CSPAN%20class%3D%22lia-inline-image-caption%22%20onclick%3D%22event.preventDefault()%3B%22%3EPlace%3C%2FSPAN%3E%3C%2FSPAN%3E%3C%2FP%3E%0A%3CP%3EWhen%20rolling%20out%20to%20bigger%20host-pools%2C%20ideally%20place%20the%20logoff%20script%20on%20a%20centrally%20accessible%20location%2C%20e.g.%20SYSVOL-share.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EHope%20this%20short%20tutorial%20will%20help%20you%20take%20full%20benefit%20of%20the%20start%20VM%20on%20connect%20feature.%20Happy%20to%20read%20your%20feedback%20and%20comments%20below.%3C%2FP%3E%3C%2FLINGO-BODY%3E%3CLINGO-SUB%20id%3D%22lingo-sub-2282490%22%20slang%3D%22en-US%22%3ERe%3A%20Deallocate%20VM%20on%20user%20logoff%3C%2FLINGO-SUB%3E%3CLINGO-BODY%20id%3D%22lingo-body-2282490%22%20slang%3D%22en-US%22%3E%3CP%3E%3CA%20href%3D%22https%3A%2F%2Ftechcommunity.microsoft.com%2Ft5%2Fuser%2Fviewprofilepage%2Fuser-id%2F830819%22%20target%3D%22_blank%22%3E%40BerndLoehlein%3C%2FA%3E%26nbsp%3BThis%20is%20awesome%20and%20I%20appreciate%20you%20sharing%20your%20scripts!%20Do%20you%20know%20if%20this%20will%20be%20baked%20into%20the%20WVD%20offering%20in%20the%20future%3F%3CBR%20%2F%3E%3CBR%20%2F%3EOne%20thing%20I%20wanted%20to%20call%20out%20for%20the%20community%20is%20you%20have%20to%20ensure%20you%20don't%20allow%20your%20users%20the%20ability%20to%20restart%20the%20VMs%20from%20within%20the%20OS%20as%20this%20will%20cause%20the%20script%20to%20kick%20off%20and%20deallocate%20the%20VMs%20without%20ever%20rebooting%20the%20VM.%20You%20can%20block%20this%20with%20a%20GPO%20as%20well.%3C%2FP%3E%3C%2FLINGO-BODY%3E%3CLINGO-SUB%20id%3D%22lingo-sub-2352926%22%20slang%3D%22en-US%22%3ERe%3A%20Deallocate%20VM%20on%20user%20logoff%3C%2FLINGO-SUB%3E%3CLINGO-BODY%20id%3D%22lingo-body-2352926%22%20slang%3D%22en-US%22%3E%3CP%3E%3CA%20href%3D%22https%3A%2F%2Ftechcommunity.microsoft.com%2Ft5%2Fuser%2Fviewprofilepage%2Fuser-id%2F1034877%22%20target%3D%22_blank%22%3E%40bking0100%3C%2FA%3E%26nbsp%3BIsn't%20it%20problematic%20to%20not%20allow%20users%20to%20restart%20the%20VM%20on%20demand%3F%26nbsp%3B%20I%20can%20see%20a%20few%20situations%20where%20for%20instance%20post%20install%20of%20software%2C%20etc.%20where%20a%20restart%20is%20needed.%26nbsp%3B%26nbsp%3B%3C%2FP%3E%3C%2FLINGO-BODY%3E
Microsoft

Recently we've announced the public preview of start VM on connect which will allow your deallocated virtual machines getting started automatically when the assigned user tries to connect. Let us have a look how we can further optimize our cost by deallocating the VM when it is not used anymore.

 

Let's first have a high level view on the needed steps:

  • Create a custom role to deallocate a virtual machine
  • Create a managed identity for your virtual machines
  • Allow each virtual machine to deallocate itself via a role assignment
  • implement logoff script and policies around idle/disconnected sessions

 

So let's start by creating our custom role:

  1. Open the Azure portal, go to Subscriptions and select the appropriate subscription

  2. Go to Access control (IAM) and select Add a custom role.
    add-custom-role.png

  3. Next, name the custom role and add a description. In this example I'll call it "Deallocate VM on logoff"

  4. On the Permissions tab, add the following permission to the subscription you're assigning the role to:

    • Microsoft.Compute/virtualMachines/deallocate/action
  5. When you're finished, select Ok.

If you prefer a JSON definition, please use the following template:

 

{
    "properties": {
        "roleName": "Deallocate VM on logoff",
        "description": "This custom role will allow your virtual machines to be deallocated when the user logs off.",
        "assignableScopes": [
            "/subscriptions/<<<SubscriptionID>>>"
        ],
        "permissions": [
            {
                "actions": [
                    "Microsoft.Compute/virtualMachines/deallocate/action"
                ],
                "notActions": [],
                "dataActions": [],
                "notDataActions": []
            }
        ]
    }
}

 

 

After we've created our custom role, we'll need to create a managed identity for our virtual machines. By this managed identities we don't need to store any credentials locally on the virtual machine or in an Azure KeyVault and can assign each virtual machine granular permission to shutdown only itself.

As this can be a bigger task, depending on the number of virtual machines you have in your personal host pools, I've prepared a script that will utilize the Azure PowerShell modules to assign that fine-grained permissions, so you may need to install those modules first:

 

Install-Module -Name Az.Account,Az.Compute,Az.DesktopVirtualization,Az.Resources

 

 

The script itself takes the host pool name, associated resource group and the role definition name selected above as parameters. It will then iterate through all virtual machines assigned to the specified host pool, create a managed identity when not already present and create a role assignment limited to the virtual machine itself:

 

$hostPoolName = "<<<HostPoolName>>>"
$resourceGroupName = "<<<ResourceGroupName>>>"
$roleDefinitionName = "<<<RoleDefinitionName>>>"

Connect-AzAccount
$sessionHosts = Get-AzWvdSessionHost -HostPoolName $hostPoolName -ResourceGroupName $resourceGroupName
foreach ($sessionHost in $sessionHosts) {
	<# get virtual machine by session host reference #>
	$resource =  Get-AzResource -ResourceId $sessionHost.ResourceId
	$vm = Get-AzVM -ResourceGroupName $resource.ResourceGroupName -Name $resource.Name
	
	<# create system-assigned managed identiy unless it already exists #>
	$managedIdentity = ($vm.Identity | where Type -eq "SystemAssigned").PrincipalId
	if ($managedIdentity -eq $Null) {
		Update-AzVM -ResourceGroupName $vm.ResourceGroupName -VM $vm -IdentityType SystemAssigned
		$managedIdentity = ((Get-AzVM -ResourceGroupName $vm.ResourceGroupName -VMName $vm.Name).Identity | where Type -eq "SystemAssigned").PrincipalId
	}
	
	<# create role-assignment unless it already exists #>
	if ((Get-AzRoleAssignment -RoleDefinitionName $roleDefinitionName -ObjectId $managedIdentity) -eq $Null) {
		New-AzRoleAssignment -ObjectId $managedIdentity -RoleDefinitionName $roleDefinitionName -Scope $vm.Id
	}
}

 

 

Next we'll configure our session host to disconnect idle sessions and logoff disconnected sessions after a certain period of time:

  1. Connect remotely to the VM that you want to set the policy for.

  2. Open the Group Policy Editor, then go to Local Computer Policy > Computer Configuration > Administrative Templates > Windows Components > Remote Desktop Services > Remote Desktop Session Host > Session Time Limits.

  3. Find the policy that says Set time limit for disconnected sessions, then change its value to Enabled.

  4. After you've enabled the policy, select your preferred time limit at End a disconnected session.

  5. Find the policy that says Set time limit for active but idle Remote Desktop Services sessions, then change its value to Enabled.
  6. After you've enabled the policy, select your preferred time limit at Idle session limit.

The above settings also ensure that an user will get a warning message two minutes before reaching the specified time limit so he can press a key or move the mouse to prevent getting disconnected.

idle-timer-expired.png

In the last step we'll create the PowerShell script initiating the deallocation and configure it as a logoff script.

 

The PowerShell script will query the details of your virtual machine using the Azure instance metadata, connect to Azure using the created managed identity and initiate the actual deallocation via REST API:

 

$metadata = Invoke-RestMethod -Headers @{"Metadata"="true"} -Method GET -Proxy $Null -Uri "http://169.254.169.254/metadata/instance?api-version=2021-01-01"
$authorizationToken = Invoke-RestMethod -Headers @{"Metadata"="true"} -Method Get -Proxy $Null -Uri "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2021-01-01&resource=https://management.azure.com/"

$subscriptionId = $metadata.compute.subscriptionId
$resourceGroupName = $metadata.compute.resourceGroupName
$vmName = $metadata.compute.name
$accessToken = $authorizationToken.access_token

Invoke-WebRequest -UseBasicParsing -Headers @{ Authorization ="Bearer $accessToken"} -Method POST -Proxy $Null -Uri https://management.azure.com/subscriptions/$subscriptionId/resourceGroups/$resourceGroupName/providers/Microsoft.Compute/virtualMachines/$vmName/deallocate?api-version=2021-03-01 -ContentType "application/json"

 

 

To have that script executed upon logoff, we need to configure it:

  1. Connect remotely to the VM that you want to set the policy for.

  2. Open the Group Policy Editor, then go to Local Computer Policy > User Configuration > Windows Settings > Scripts (Logon/Logoff).

  3. Find the item that says Logoff.

  4. Specify the script you've created on the PowerShell Scripts tab.

PlacePlace

When rolling out to bigger host-pools, ideally place the logoff script on a centrally accessible location, e.g. SYSVOL-share.

 

Hope this short tutorial will help you take full benefit of the start VM on connect feature. Happy to read your feedback and comments below.

2 Replies

@BerndLoehlein This is awesome and I appreciate you sharing your scripts! Do you know if this will be baked into the WVD offering in the future?

One thing I wanted to call out for the community is you have to ensure you don't allow your users the ability to restart the VMs from within the OS as this will cause the script to kick off and deallocate the VMs without ever rebooting the VM. You can block this with a GPO as well.

@bking0100 Isn't it problematic to not allow users to restart the VM on demand?  I can see a few situations where for instance post install of software, etc. where a restart is needed.