Search code examples
powershellazurechocolateyazure-rm-template

ARM template deploy w/ Chocolatey CSE fails on PS script


I have been following along with this ARM template to build a VM and deploy apps via Chocolatey:

https://github.com/Azure/azure-quickstart-templates/tree/master/visual-studio-dev-vm-chocolatey

Despite the extension on GitHub showing as a Linux extension, not a MS one (I changed it in mine), I am successful in deploying the VM. However, the PowerShell automation script for installing Chocolatey fails.

Long story short, I have discovered that it works perfectly fine on Server 2012, but it will not work on Server 2016.

Here is the PowerShell script:

param([Parameter(Mandatory=$true)][string]$chocoPackages)
cls

#New-Item "c:\jdchoco" -type Directory -force | Out-Null
#$LogFile = "c:\jdchoco\JDScript.log"
#$chocoPackages | Out-File $LogFile -Append

# Get username/password & machine name
$userName = "artifactInstaller"
[Reflection.Assembly]::LoadWithPartialName("System.Web") | Out-Null
$password = $([System.Web.Security.Membership]::GeneratePassword(12,4))
$cn = [ADSI]"WinNT://$env:ComputerName"

# Create new user
$user = $cn.Create("User", $userName)
$user.SetPassword($password)
$user.SetInfo()
$user.description = "Choco artifact installer"
$user.SetInfo()

# Add user to the Administrators group
$group = [ADSI]"WinNT://$env:ComputerName/Administrators,group"
$group.add("WinNT://$env:ComputerName/$userName")

# Create pwd and new $creds for remoting
$secPassword = ConvertTo-SecureString $password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential("$env:COMPUTERNAME\$($username)", $secPassword)

# Ensure that current process can run scripts. 
#"Enabling remoting" | Out-File $LogFile -Append
Enable-PSRemoting -Force -SkipNetworkProfileCheck

#"Changing ExecutionPolicy" | Out-File $LogFile -Append
Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process -Force

# Install Choco
#"Installing Chocolatey" | Out-File $LogFile -Append
$sb = { iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1')) }
Invoke-Command -ScriptBlock $sb -ComputerName $env:COMPUTERNAME -Credential $credential | Out-Null

#"Disabling UAC" | Out-File $LogFile -Append
$sb = { Set-ItemProperty -path HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System -name EnableLua -value 0 }
Invoke-Command -ScriptBlock $sb -ComputerName $env:COMPUTERNAME -Credential $credential

#"Install each Chocolatey Package"
$chocoPackages.Split(";") | ForEach {
    $command = "cinst " + $_ + " -y -force"
    $command | Out-File $LogFile -Append
    $sb = [scriptblock]::Create("$command")

    # Use the current user profile
    Invoke-Command -ScriptBlock $sb -ArgumentList $chocoPackages -ComputerName $env:COMPUTERNAME -Credential $credential | Out-Null
}

Disable-PSRemoting -Force

# Delete the artifactInstaller user
$cn.Delete("User", $userName)

# Delete the artifactInstaller user profile
gwmi win32_userprofile | where { $_.LocalPath -like "*$userName*" } | foreach { $_.Delete() }

If I were to open up PowerShell ISE and run it directly on a Server 2016 machine I am prompted with the following error(s):

[asdf] Connecting to remote server asdf failed with the following error message : Access is denied. For more information, 
see the about_Remote_Troubleshooting Help topic.
    + CategoryInfo          : OpenError: (asdf:String) [], PSRemotingTransportException
    + FullyQualifiedErrorId : AccessDenied,PSSessionStateBroken
[asdf] Connecting to remote server asdf failed with the following error message : Access is denied. For more information, 
see the about_Remote_Troubleshooting Help topic.
    + CategoryInfo          : OpenError: (asdf:String) [], PSRemotingTransportException
    + FullyQualifiedErrorId : AccessDenied,PSSessionStateBroken
Out-File : Cannot bind argument to parameter 'FilePath' because it is null.
At line:48 char:25
+     $command | Out-File $LogFile -Append
+                         ~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Out-File], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.OutFileCommand

[asdf] Connecting to remote server asdf failed with the following error message : Access is denied. For more information, 
see the about_Remote_Troubleshooting Help topic.
    + CategoryInfo          : OpenError: (asdf:String) [], PSRemotingTransportException
    + FullyQualifiedErrorId : AccessDenied,PSSessionStateBroken

'asdf' is the name of the machine

I am able to run the code step by step, but it will always fail on:

Invoke-Command -ScriptBlock $sb -ComputerName $env:COMPUTERNAME -Credential $credential

I can see that the account gets created, a password is created, it is assigned admin rights, but I guess somewhere it just doesn't like how the credentials as passed into the command. Why this works for 2012 and not 2016, I have no idea. I'm no PowerShell guru, so any help would be appreciated, please.


Solution

  • To answer my own question, it seems I had to run winrm quickconfig which enabled the following key in registry:

    "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\"
    -Name 'LocalAccountTokenFilterPolicy' -Value '1' -PropertyType 'DWord'
    

    So I adjusted the script to include the following snippets before and after the actions.

    Before:

    # Enable LocalAccountTokenFilterPolicy
    $LocalAccToken1 = Get-Item -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\"
    If(!($LocalAccToken1.GetValue("LocalAccountTokenFilterPolicy") -eq 1)) {
        New-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' `
        -Name 'LocalAccountTokenFilterPolicy' -Value '1' -PropertyType 'DWord' -Force
    }
    

    After (I removed the setting 'just in case' of nefarious activity that can stem from it):

    # Disable LocalAccountTokenFilterPolicy
    $LocalAccToken2 = Get-Item -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\"
    If($LocalAccToken2.GetValue("LocalAccountTokenFilterPolicy") -eq 1) {
        Remove-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' `
        -Name 'LocalAccountTokenFilterPolicy' -Force
        }
    

    ...I hope MS update their template.