SOLVED

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%3CLINGO-SUB%20id%3D%22lingo-sub-2457781%22%20slang%3D%22en-US%22%3ERe%3A%20Deallocate%20VM%20on%20user%20logoff%3C%2FLINGO-SUB%3E%3CLINGO-BODY%20id%3D%22lingo-body-2457781%22%20slang%3D%22en-US%22%3E%3CP%3E%3CA%20href%3D%22https%3A%2F%2Ftechcommunity.microsoft.com%2Ft5%2Fuser%2Fviewprofilepage%2Fuser-id%2F659950%22%20target%3D%22_blank%22%3E%40WVDExpert%3C%2FA%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EAssignments%20of%20roles%20requires%20the%26nbsp%3BMicrosoft.Authorization%2FroleAssignments%2Fwrite%20permissions%20which%20are%20only%20included%20in%20the%20pre-defined%20roles%20of%20%22User%20Access%20Administrator%22%20or%20%22Owner%22.%3C%2FP%3E%3C%2FLINGO-BODY%3E%3CLINGO-SUB%20id%3D%22lingo-sub-2593733%22%20slang%3D%22en-US%22%3ERe%3A%20Deallocate%20VM%20on%20user%20logoff%3C%2FLINGO-SUB%3E%3CLINGO-BODY%20id%3D%22lingo-body-2593733%22%20slang%3D%22en-US%22%3EI've%20updated%20the%20script%20in%20above%20post%20to%20check%20if%20the%20user%20has%20initiated%20a%20reboot%20or%20another%20user%20is%20still%20active%20on%20the%20same%20machine.%20Deallocation%20won't%20be%20initiated%20in%20those%20cases.%3C%2FLINGO-BODY%3E%3CLINGO-SUB%20id%3D%22lingo-sub-2595766%22%20slang%3D%22en-US%22%3ERe%3A%20Deallocate%20VM%20on%20user%20logoff%3C%2FLINGO-SUB%3E%3CLINGO-BODY%20id%3D%22lingo-body-2595766%22%20slang%3D%22en-US%22%3EHi%20%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%20%2C%20thank%20you%20heaps%20for%20this%20and%20it%20works%20like%20a%20charm%20for%20the%20VMs%20we%20use%20in%20our%20host%20pool.%20Just%20wanted%20to%20ask%20if%20there's%20a%20way%20to%20automate%20the%20deployment%20of%20this%20group%20policy%20somehow%20in%20Azure%2C%20rather%20than%20remoting%20into%20the%20VM%20and%20setting%20the%20policies%20manually%3F%3C%2FLINGO-BODY%3E%3CLINGO-SUB%20id%3D%22lingo-sub-2596117%22%20slang%3D%22en-US%22%3ERe%3A%20Deallocate%20VM%20on%20user%20logoff%3C%2FLINGO-SUB%3E%3CLINGO-BODY%20id%3D%22lingo-body-2596117%22%20slang%3D%22en-US%22%3E%3CP%3EHi%26nbsp%3B%3CA%20href%3D%22https%3A%2F%2Ftechcommunity.microsoft.com%2Ft5%2Fuser%2Fviewprofilepage%2Fuser-id%2F1116103%22%20target%3D%22_blank%22%3E%40krayste%3C%2FA%3E%2C%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EFor%20an%20AD-joined%20host%20pool%20I%20would%20recommend%20configuring%20the%20mentioned%20settings%20via%20central%20group%20policy%20and%20targeting%20this%20to%20the%20OU%20where%20your%20session-hosts%20reside.%20You%20would%20then%20also%20make%20the%20script%20accessible%20on%20a%20central%20location%2C%20e.g.%20the%20SYSVOL%20share%2C%20so%20you%20don't%20need%20to%20deploy%20the%20script%20on%20every%20host.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EFor%20AAD-only%20environments%20there%20may%20be%20an%20option%20to%20automate%20it%20using%20MEM%2FIntune.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3ERegards%2C%3C%2FP%3E%0A%3CP%3EBernd%3C%2FP%3E%3C%2FLINGO-BODY%3E%3CLINGO-SUB%20id%3D%22lingo-sub-2639538%22%20slang%3D%22en-US%22%3ERe%3A%20Deallocate%20VM%20on%20user%20logoff%3C%2FLINGO-SUB%3E%3CLINGO-BODY%20id%3D%22lingo-body-2639538%22%20slang%3D%22en-US%22%3EI've%20been%20having%20an%20issue%20with%20this%2C%20so%20much%20so%20I've%20had%20to%20use%20a%20different%20method.%20What%20happens%20when%20users%20log%20out%20is%20that%20the%20user%20session%20is%20not%20correctly%20removed.%20This%20means%20when%20they%20try%20to%20login%20thier%20VM%20doesn't%20start.%20We%20get%20the%20error%20ConnectionFailedUserHasValidSessionButRdshIsUnhealthy%20(-2146233088).%3CBR%20%2F%3E%3C%2FLINGO-BODY%3E%3CLINGO-SUB%20id%3D%22lingo-sub-2674252%22%20slang%3D%22en-US%22%3ERe%3A%20Deallocate%20VM%20on%20user%20logoff%3C%2FLINGO-SUB%3E%3CLINGO-BODY%20id%3D%22lingo-body-2674252%22%20slang%3D%22en-US%22%3E%3CP%3E%3CA%20href%3D%22https%3A%2F%2Ftechcommunity.microsoft.com%2Ft5%2Fuser%2Fviewprofilepage%2Fuser-id%2F520873%22%20target%3D%22_blank%22%3E%40HenryGelderbloem%3C%2FA%3E%26nbsp%3BYou%20use%20the%20actually%20Remote%20Desktop%20App%20Version%3F%3C%2FP%3E%3C%2FLINGO-BODY%3E%3CLINGO-SUB%20id%3D%22lingo-sub-2724001%22%20slang%3D%22en-US%22%3ERe%3A%20Deallocate%20VM%20on%20user%20logoff%3C%2FLINGO-SUB%3E%3CLINGO-BODY%20id%3D%22lingo-body-2724001%22%20slang%3D%22en-US%22%3EMy%20workaround%20was%20to%20not%20use%20this%20method%20at%20all.%20I%20have%20configured%20it%20in%20a%20way%20that%20shuts%20down%20the%20VM%20if%20the%20user%20logs%20out%20(or%20is%20logged%20out%20due%20to%20being%20idle).%20I%20then%20have%20an%20Azure%20Function%20that%20runs%20every%2030%20minutes%20and%20checks%20for%20VMs%20that%20are%20powered%20off%20but%20not%20deallocated.%20If%20they%20are%20powered%20off%20but%20not%20deallocated%2C%20they%20are%20then%20deallocated.%3C%2FLINGO-BODY%3E%3CLINGO-SUB%20id%3D%22lingo-sub-2767393%22%20slang%3D%22en-US%22%3ERe%3A%20Deallocate%20VM%20on%20user%20logoff%3C%2FLINGO-SUB%3E%3CLINGO-BODY%20id%3D%22lingo-body-2767393%22%20slang%3D%22en-US%22%3E%3CP%3E%3CA%20href%3D%22https%3A%2F%2Ftechcommunity.microsoft.com%2Ft5%2Fuser%2Fviewprofilepage%2Fuser-id%2F520873%22%20target%3D%22_blank%22%3E%40HenryGelderbloem%3C%2FA%3E%26nbsp%3B%3CA%20href%3D%22https%3A%2F%2Ftechcommunity.microsoft.com%2Ft5%2Fuser%2Fviewprofilepage%2Fuser-id%2F1142530%22%20target%3D%22_blank%22%3E%40PatrickBrack%3C%2FA%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3ECould%20you%20please%20try%20to%20update%20the%20custom%20role%20used%20for%20Start%20VM%20on%20Connect%20and%20add%26nbsp%3BMicrosoft.Compute%2FvirtualMachines%2FinstanceView%2Fread%20to%20it%3F%20This%20should%20ensure%20that%20sessions%20are%20removed%20in%20the%20service%20upon%20deallocation%20of%20the%20virtual%20machine.%3C%2FP%3E%0A%3CP%3E%26nbsp%3B%3C%2FP%3E%0A%3CP%3EWe've%20already%20updated%20our%20%3CA%20href%3D%22https%3A%2F%2Fdocs.microsoft.com%2Fen-us%2Fazure%2Fvirtual-desktop%2Fstart-virtual-machine-connect%23create-a-custom-role-for-start-vm-on-connect%22%20target%3D%22_self%22%20rel%3D%22noopener%20noreferrer%22%3Edocs%20for%20Start%20VM%20on%20Connect%3C%2FA%3E%2C%20but%20could%20be%20easily%20missed%20by%20customers%20already%20using%20this%20feature.%3C%2FP%3E%3C%2FLINGO-BODY%3E%3CLINGO-SUB%20id%3D%22lingo-sub-2674804%22%20slang%3D%22en-US%22%3ERe%3A%20Deallocate%20VM%20on%20user%20logoff%3C%2FLINGO-SUB%3E%3CLINGO-BODY%20id%3D%22lingo-body-2674804%22%20slang%3D%22en-US%22%3E%3CP%3E%3CA%20href%3D%22https%3A%2F%2Ftechcommunity.microsoft.com%2Ft5%2Fuser%2Fviewprofilepage%2Fuser-id%2F659950%22%20target%3D%22_blank%22%3E%40WVDExpert%3C%2FA%3E%26nbsp%3BWe%20do%2C%20and%20it%20happens%20on%20different%20OSes%20too.%20SO%20the%20macOS%20and%20Windows%20version%20are%20affected%20as%20well%20as%20the%20iPadOS%20version.%3C%2FP%3E%3C%2FLINGO-BODY%3E%3CLINGO-SUB%20id%3D%22lingo-sub-2454178%22%20slang%3D%22en-US%22%3ERe%3A%20Deallocate%20VM%20on%20user%20logoff%3C%2FLINGO-SUB%3E%3CLINGO-BODY%20id%3D%22lingo-body-2454178%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%3B%3CBR%20%2F%3E%3CBR%20%2F%3Every%20good%20solution.%20Thank%20you.%3CBR%20%2F%3E%3CBR%20%2F%3E%3C%2FP%3E%3CP%3EI%20try%20to%20implement%20the%20script%20fro%20create%20managedid%20and%20AzRoleAssgniment%20in%20a%20azure%20function.%26nbsp%3B%3CBR%20%2F%3EWhich%20Azure%20Role%20permission%20i%20need%20for%3A%3C%2FP%3E%3CPRE%3ENew-AzRoleAssignment%20-ObjectId%20%24managedIdentity%20-RoleDefinitionName%20%24roleDefinitionName%20-Scope%20%24vm.Id%3C%2FPRE%3E%3CP%3E%26nbsp%3BBecause%20i%20become%20the%20following%20error%3A%3CBR%20%2F%3ENew-AzRoleAssignmentParameterSetName%20%3A%20EmptyParameterSetContent-Type%20%3A%20application%2Fjson%3B%20charset%3Dutf-8Content-Length%20%3A%20116Response%20%3AStatusCode%20%3A%20ForbiddenReasonPhrase%20%3A%20ForbiddenContent%20%3A%20%7B%22odata.error%22%3A%7B%22code%22%3A%22Authorization_RequestDenied%22%2C%22message%22%3A%7B%22lang%22%3A%22en%22%2C%22value%22%3A%22Insufficient%20privileges%20to%20complete%20the%20operation.%22%7D%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

$RestartEvents = Get-EventLog -LogName System -After (Get-Date).AddMinutes(-1) |? {($_.EventID -eq 1074) -and ($_.Message -match "restart" )}
$SessionCount = (query user | Measure-Object | select Count).count - 1 # remove headline

if (($SessionCount -gt 1) -or ($RestartEvents.count -ge 1))
{
	# skip deallocate because of user-sessions or initiated reboot
} else {
	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.

13 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.  

@BerndLoehlein 

very good solution. Thank you.

I try to implement the script fro create managedid and AzRoleAssgniment in a azure function. 
Which Azure Role permission i need for:

New-AzRoleAssignment -ObjectId $managedIdentity -RoleDefinitionName $roleDefinitionName -Scope $vm.Id

 Because i become the following error:
New-AzRoleAssignmentParameterSetName : EmptyParameterSetContent-Type : application/json; charset=utf-8Content-Length : 116Response :StatusCode : ForbiddenReasonPhrase : ForbiddenContent : {"odata.error":{"code":"Authorization_RequestDenied","message":{"lang":"en","value":"Insufficient privileges to complete the operation."}

@WVDExpert 

 

Assignments of roles requires the Microsoft.Authorization/roleAssignments/write permissions which are only included in the pre-defined roles of "User Access Administrator" or "Owner".

I've updated the script in above post to check if the user has initiated a reboot or another user is still active on the same machine. Deallocation won't be initiated in those cases.
Hi @BerndLoehlein , thank you heaps for this and it works like a charm for the VMs we use in our host pool. Just wanted to ask if there's a way to automate the deployment of this group policy somehow in Azure, rather than remoting into the VM and setting the policies manually?

Hi @krayste,

 

For an AD-joined host pool I would recommend configuring the mentioned settings via central group policy and targeting this to the OU where your session-hosts reside. You would then also make the script accessible on a central location, e.g. the SYSVOL share, so you don't need to deploy the script on every host.

 

For AAD-only environments there may be an option to automate it using MEM/Intune.

 

Regards,

Bernd

I've been having an issue with this, so much so I've had to use a different method. What happens when users log out is that the user session is not correctly removed. This means when they try to login thier VM doesn't start. We get the error ConnectionFailedUserHasValidSessionButRdshIsUnhealthy (-2146233088).

@HenryGelderbloem You use the actually Remote Desktop App Version?

@WVDExpert We do, and it happens on different OSes too. SO the macOS and Windows version are affected as well as the iPadOS version.

@HenryGelderbloem same here. Tried also an option with an Azure Function which checks for active sessions and shut down the VM with the Stop-AzVM PowerShell command. Same issue. The start on connect feature throws the same error. 

Can you probably share which method you finally used to avoid this error?  

My workaround was to not use this method at all. I have configured it in a way that shuts down the VM if the user logs out (or is logged out due to being idle). I then have an Azure Function that runs every 30 minutes and checks for VMs that are powered off but not deallocated. If they are powered off but not deallocated, they are then deallocated.
best response confirmed by Eva Seydl (Microsoft)
Solution

@HenryGelderbloem @PatrickBrack 

Could you please try to update the custom role used for Start VM on Connect and add Microsoft.Compute/virtualMachines/instanceView/read to it? This should ensure that sessions are removed in the service upon deallocation of the virtual machine.

 

We've already updated our docs for Start VM on Connect, but could be easily missed by customers already using this feature.