MY PACKER SHIT WORKS!!

- Remove all scripts I'm not using
- (All scripts still in legacy-packer-windows folder tho)
- Postinstall PS module now does EVERYTHING that old scripts were doing
- Eliminate need for SSH altogether
jowjDev
Micah R Ledbetter 9 years ago
parent 1230ab9829
commit 5b5cc98dd3

@ -83,10 +83,13 @@ function Add-BoxToVagrant {
param(
[parameter(mandatory=$true)] $vagrantBoxName,
[parameter(mandatory=$true)] $packedBoxPath,
[switch] $force,
[switch] $whatIf
)
if (-not $whatIf) {
vagrant box add --name $vagrantBoxName $packedBoxPath
$forceOption = ""
if ($force) { $forceOption = "--force" }
vagrant box add $forceOption --name $vagrantBoxName $packedBoxPath
if ($LASTEXITCODE -ne 0) { throw "External command failed with code '$LASTEXITCODE'" }
}
}
@ -155,8 +158,8 @@ if ($action -contains "BuildPacker") {
Build-PackerFile @bpfParam
}
if ($action -contains "AddToVagrant") {
Add-BoxToVagrant -vagrantBoxName $fullConfigName -packedBoxPath $packedBoxPath
Add-BoxToVagrant -vagrantBoxName $fullConfigName -packedBoxPath $packedBoxPath -force:$force -whatif:$whatif
}
if ($action -contains "VagrantUp") {
Run-VagrantBox -vagrantBoxName $fullConfigName -workingDirectory $outDir
Run-VagrantBox -vagrantBoxName $fullConfigName -workingDirectory $outDir -whatif:$whatif
}

@ -1,3 +0,0 @@
*.exe
*.msi
*.msu

@ -1,6 +0,0 @@
if not exist "C:\Windows\Temp\chef.msi" (
powershell -Command "(New-Object System.Net.WebClient).DownloadFile('http://www.getchef.com/chef/install.msi', 'C:\Windows\Temp\chef.msi')" <NUL
)
msiexec /qb /i C:\Windows\Temp\chef.msi
powershell -Command "Start-Sleep 1" <NUL

@ -1,22 +0,0 @@
$chocoExePath = 'C:\ProgramData\Chocolatey\bin'
if ($($env:Path).ToLower().Contains($($chocoExePath).ToLower())) {
echo "Chocolatey found in PATH, skipping install..."
Exit
}
# Add to system PATH
$systemPath = [Environment]::GetEnvironmentVariable('Path',[System.EnvironmentVariableTarget]::Machine)
$systemPath += ';' + $chocoExePath
[Environment]::SetEnvironmentVariable("PATH", $systemPath, [System.EnvironmentVariableTarget]::Machine)
# Update local process' path
$userPath = [Environment]::GetEnvironmentVariable('Path',[System.EnvironmentVariableTarget]::User)
if($userPath) {
$env:Path = $systemPath + ";" + $userPath
} else {
$env:Path = $systemPath
}
# Run the installer
iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))

@ -1,45 +0,0 @@
set TEMPTEMP=C:\PackerTemp
mkdir %TEMPTEMP%
reg Query "HKLM\Hardware\Description\System\CentralProcessor\0" | find /i "x86" > NUL && set OSARCHITECTURE=32BIT || set OSARCHITECTURE=64BIT
echo OSARCHITECTURE == %OSARCHITECTURE%
set UDFARCH=i386
if %OSARCHITECTURE%==64BIT set UDFARCH=amd64
echo UDFARCH == %UDFARCH%
set UDFFILENAME=ultradefrag-portable-6.1.0.bin.%UDFARCH%.zip
set UDFURL=http://downloads.sourceforge.net/project/ultradefrag/stable-release/6.1.0/%UDFFILENAME%
set UDFZIP=%TEMPTEMP%\%UDFFILENAME%
set UDFEXE=%TEMPTEMP%\ultradefrag-portable-6.1.0.%UDFARCH%\udefrag.exe
if not exist "%UDFZIP%" (
powershell -Command "(New-Object System.Net.WebClient).DownloadFile('%UDFURL%', '%UDFZIP%')" <NUL
)
if not exist "%UDFEXE%" (
cmd /c ""C:\Program Files\7-Zip\7z.exe" x %UDFZIP% -o%TEMPTEMP%"
)
if not exist "%TEMPTEMP%\SDelete.zip" (
powershell -Command "(New-Object System.Net.WebClient).DownloadFile('http://download.sysinternals.com/files/SDelete.zip', '%TEMPTEMP%\SDelete.zip')" <NUL
)
if not exist "%TEMPTEMP%\sdelete.exe" (
cmd /c ""C:\Program Files\7-Zip\7z.exe" x %TEMPTEMP%\SDelete.zip -o%TEMPTEMP%"
)
@echo ========================================
@echo ALL THE FILES IN MY TEMP DIRECTORY OF "%TEMPTEMP%"
@dir %TEMPTEMP%
@echo ========================================
net stop wuauserv
rmdir /S /Q C:\Windows\SoftwareDistribution\Download
mkdir C:\Windows\SoftwareDistribution\Download
net start wuauserv
cmd /c %UDFEXE% --optimize --repeat C:
cmd /c %SystemRoot%\System32\reg.exe ADD HKCU\Software\Sysinternals\SDelete /v EulaAccepted /t REG_DWORD /d 1 /f
cmd /c %TEMPTEMP%\sdelete.exe -q -z C:
rmdir /s /q %TEMPTEMP%

@ -1,15 +0,0 @@
::http://support.microsoft.com/kb/2570538
::http://robrelyea.wordpress.com/2007/07/13/may-be-helpful-ngen-exe-executequeueditems/
if "%PROCESSOR_ARCHITECTURE%"=="AMD64" goto 64BIT
%windir%\microsoft.net\framework\v4.0.30319\ngen.exe update /force /queue
%windir%\microsoft.net\framework\v4.0.30319\ngen.exe executequeueditems
exit /b
:64BIT
%windir%\microsoft.net\framework\v4.0.30319\ngen.exe update /force /queue
%windir%\microsoft.net\framework64\v4.0.30319\ngen.exe update /force /queue
%windir%\microsoft.net\framework\v4.0.30319\ngen.exe executequeueditems
%windir%\microsoft.net\framework64\v4.0.30319\ngen.exe executequeueditems

@ -1,30 +0,0 @@
<#
.SYNOPSIS
Disables automatic windows updates
.DESCRIPTION
Disables checking for and applying Windows Updates (does not prevent updates from being applied manually or being pushed down)
Run on the machine that updates need disabling on.
.PARAMETER <paramName>
None
.EXAMPLE
./Disable-WindowsUpdates.ps1
#>
$RunningAsAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
if ($RunningAsAdmin)
{
$Updates = (New-Object -ComObject "Microsoft.Update.AutoUpdate").Settings
if ($Updates.ReadOnly -eq $True) { Write-Error "Cannot update Windows Update settings due to GPO restrictions." }
else {
$Updates.NotificationLevel = 1 #Disabled
$Updates.Save()
$Updates.Refresh()
Write-Output "Automatic Windows Updates disabled."
}
}
else
{ Write-Warning "Must be executed in Administrator level shell."
Write-Warning "Script Cancelled!" }

@ -1 +0,0 @@
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v AutoAdminLogon /d 0 /f

@ -1,2 +0,0 @@
netsh advfirewall firewall add rule name="Open Port 3389" dir=in action=allow protocol=TCP localport=3389
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f

@ -1,7 +0,0 @@
reg Query "HKLM\Hardware\Description\System\CentralProcessor\0" | find /i "x86" > NUL && set OSARCHITECTURE=32BIT || set OSARCHITECTURE=64BIT
set SZFILENAME=7z920.msi
if %OSARCHITECTURE%==64BIT set SZFILENAME=7z920-x64.msi
set SZURL=http://7-zip.org/a/%SZFILENAME%
set SZDLPATH=C:\Windows\Temp\%SZFILENAME%
powershell -Command "(New-Object System.Net.WebClient).DownloadFile('%SZURL%', '%SZDLPATH%')" <NUL
echo msiexec /qb /i %SZDLPATH%

@ -1,87 +0,0 @@
param (
[switch]$AutoStart = $false
)
Write-Output "AutoStart: $AutoStart"
$is_64bit = [IntPtr]::size -eq 8
# setup openssh
$ssh_download_url = "http://www.mls-software.com/files/setupssh-6.7p1-2.exe"
if (!(Test-Path "C:\Program Files\OpenSSH\bin\ssh.exe")) {
Write-Output "Downloading $ssh_download_url"
(New-Object System.Net.WebClient).DownloadFile($ssh_download_url, "C:\Windows\Temp\openssh.exe")
# initially set the port to 2222 so that there is not a race
# condition in which packer connects to SSH before we can disable the service
Start-Process "C:\Windows\Temp\openssh.exe" "/S /port=2222 /privsep=1 /password=D@rj33l1ng" -NoNewWindow -Wait
}
Stop-Service "OpenSSHd" -Force
# ensure vagrant can log in
Write-Output "Setting vagrant user file permissions"
New-Item -ItemType Directory -Force -Path "C:\Users\vagrant\.ssh"
C:\Windows\System32\icacls.exe "C:\Users\vagrant" /grant "vagrant:(OI)(CI)F"
C:\Windows\System32\icacls.exe "C:\Program Files\OpenSSH\bin" /grant "vagrant:(OI)RX"
C:\Windows\System32\icacls.exe "C:\Program Files\OpenSSH\usr\sbin" /grant "vagrant:(OI)RX"
Write-Output "Setting SSH home directories"
(Get-Content "C:\Program Files\OpenSSH\etc\passwd") |
Foreach-Object { $_ -replace '/home/(\w+)', '/cygdrive/c/Users/$1' } |
Set-Content 'C:\Program Files\OpenSSH\etc\passwd'
# Set shell to /bin/sh to return exit status
$passwd_file = Get-Content 'C:\Program Files\OpenSSH\etc\passwd'
$passwd_file = $passwd_file -replace '/bin/bash', '/bin/sh'
Set-Content 'C:\Program Files\OpenSSH\etc\passwd' $passwd_file
# fix opensshd to not be strict
Write-Output "Setting OpenSSH to be non-strict"
$sshd_config = Get-Content "C:\Program Files\OpenSSH\etc\sshd_config"
$sshd_config = $sshd_config -replace 'StrictModes yes', 'StrictModes no'
$sshd_config = $sshd_config -replace '#PubkeyAuthentication yes', 'PubkeyAuthentication yes'
$sshd_config = $sshd_config -replace '#PermitUserEnvironment no', 'PermitUserEnvironment yes'
# disable the use of DNS to speed up the time it takes to establish a connection
$sshd_config = $sshd_config -replace '#UseDNS yes', 'UseDNS no'
# disable the login banner
$sshd_config = $sshd_config -replace 'Banner /etc/banner.txt', '#Banner /etc/banner.txt'
# next time OpenSSH starts have it listen on th eproper port
$sshd_config = $sshd_config -replace 'Port 2222', "Port 22"
Set-Content "C:\Program Files\OpenSSH\etc\sshd_config" $sshd_config
Write-Output "Removing ed25519 key as Vagrant net-ssh 2.9.1 does not support it"
Remove-Item -Force -ErrorAction SilentlyContinue "C:\Program Files\OpenSSH\etc\ssh_host_ed25519_key"
Remove-Item -Force -ErrorAction SilentlyContinue "C:\Program Files\OpenSSH\etc\ssh_host_ed25519_key.pub"
# use c:\Windows\Temp as /tmp location
Write-Output "Setting temp directory location"
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue "C:\Program Files\OpenSSH\tmp"
C:\Program` Files\OpenSSH\bin\junction.exe /accepteula "C:\Program Files\OpenSSH\tmp" "C:\Windows\Temp"
C:\Windows\System32\icacls.exe "C:\Windows\Temp" /grant "vagrant:(OI)(CI)F"
# add 64 bit environment variables missing from SSH
Write-Output "Setting SSH environment"
$sshenv = "TEMP=C:\Windows\Temp"
if ($is_64bit) {
$env_vars = "ProgramFiles(x86)=C:\Program Files (x86)", `
"ProgramW6432=C:\Program Files", `
"CommonProgramFiles(x86)=C:\Program Files (x86)\Common Files", `
"CommonProgramW6432=C:\Program Files\Common Files"
$sshenv = $sshenv + "`r`n" + ($env_vars -join "`r`n")
}
Set-Content C:\Users\vagrant\.ssh\environment $sshenv
# record the path for provisioners (without the newline)
Write-Output "Recording PATH for provisioners"
Set-Content C:\Windows\Temp\PATH ([byte[]][char[]] $env:PATH) -Encoding Byte
# configure firewall
Write-Output "Configuring firewall"
netsh advfirewall firewall add rule name="SSHD" dir=in action=allow service=OpenSSHd enable=yes
netsh advfirewall firewall add rule name="SSHD" dir=in action=allow program="C:\Program Files\OpenSSH\usr\sbin\sshd.exe" enable=yes
netsh advfirewall firewall add rule name="ssh" dir=in action=allow protocol=TCP localport=22
if ($AutoStart -eq $true) {
Start-Service "OpenSSHd"
}

Binary file not shown.

@ -0,0 +1,63 @@
<#
Fucking Packer is giving me problems with its shell, windows-shell, and powershell provisioners, so fuck it
Don't require parameters - it won't run with parameters during post install. This is just for clarity & ease of debugging
#>
[cmdletbinding()]
param(
$packerBuildName = ${env:PACKER_BUILD_NAME},
$packerBuilderType = ${env:PACKER_BUILDER_TYPE},
$tempDir = ${env:WinTrialLabTemp} # calculated later on if this is empty
)
$errorActionPreference = "stop"
write-verbose "PostInstall for packer build '$packerBuildName' of type '$packerBuilderType'"
if ($packerBuilderType -notmatch "virtualbox") {
$warning = "@@@WARNING@@@ I have no way to install tools for your selected Packer build type of '$packerBuilderType'"
write-host -foreground red -object $warning
}
$LASTEXITCODE = 0 # just in case
# Wrap all my function calls in try/finally to remove the temp dir
if ($tempDir) { $env:WinTrialLabTemp = $tempDir }
import-module $PSScriptRoot\wintriallab-postinstall.psm1
try {
Install-SevenZip
#Install-VBoxAdditions -isoPath "C:\Users\vagrant\VBoxGuestAdditions.iso"
Install-VBoxAdditions -fromDisc
Disable-AutoAdminLogon
Enable-RDP
#Install-VagrantSshKey
Install-Chocolatey
$suoParams = @{
ShowHiddenFiles = $true
ShowSystemFiles = $true
ShowFileExtensions = $true
ShowStatusBar = $true
DisableSharingWizard = $true
EnablePSOnWinX = $true
EnableQuickEdit = $true
}
Set-UserOptions @suoParams
Install-CompiledDotNetAssemblies # Takes about 15 minutes for me
Compress-WindowsInstall # Takes maybe another 15 minutes
}
catch {
write-host "======== CAUGHT EXCEPTION ========"
write-host "$_"
write-host "======== CALL STACK ========"
Get-PSCallStack | format-list
write-host "======== ERROR STACK ========"
Show-ErrorReport
write-host "======== ========"
exit 666
}
finally {
write-host "THE END"
#rm -recurse -force (Get-LabTempDir)
}

@ -0,0 +1,423 @@
<#
jesus fucking christ
fucking Packer
#>
<#
TODO: make sure this is always a 100% normalized path
#>
function Get-LabTempDir {
write-verbose "Function: $($MyInvocation.MyCommand)..."
if ("${script:WinTrialLabTemp}") {}
elseif ("${env:WinTrialLabTemp}") {
$script:WinTrialLabTemp = $env:WinTrialLabTemp
}
else {
$dateStamp = get-date -UFormat "%Y-%m-%d-%H-%M-%S"
$script:WinTrialLabTemp = "${env:Temp}\WinTrialLab-$dateStamp"
}
if (-not (test-path $script:WinTrialLabTemp)) {
write-verbose "Temporary directory does not exist, creating it..."
mkdir -force $script:WinTrialLabTemp | out-null
}
$script:WinTrialLabTemp = resolve-path $script:WinTrialLabTemp | select -expand Path
write-verbose "Using WinTrialLabTemp directory at '${script:WinTrialLabTemp}'"
return $script:WinTrialLabTemp
}
function Get-WebUrl {
param(
[parameter(mandatory=$true)] [string] $url,
[parameter(mandatory=$true)] [string] $downloadPath
)
write-verbose "Function: $($MyInvocation.MyCommand)..."
if (test-path $downloadPath) {
if ((get-item $downloadPath).gettype().name -match "DirectoryInfo") {
throw "Must provide a full path, including filename"
}
else {
$downloadPath = resolve-path $downloadPath | select -expand path
}
}
else {
$downloadParent = split-path $downloadPath -parent
$downloadFilename = split-path $downloadPath -leaf
if (-not "$downloadParent") {
$downloadParent = $pwd | select -expand Path
}
elseif (-not (test-path $downloadParent)) {
mkdir -force $downloadParent | out-null
}
$downloadParent = resolve-path $downloadParent
$downloadPath = "$downloadParent\$downloadFilename" -replace ""
}
write-verbose "Downloading url '$url' to path '$downloadPath'"
(New-Object System.Net.WebClient).DownloadFile($url, $downloadPath)
}
<#
.description
Return the OS Architecture, as determined by WMI
Will return either "i386" or "amd64"
TODO: this isn't a great method but I'm tired of trying to find the totally correct one. This one isn't ideal because OSArchitecture can be localized.
Supposedly the canonical way is calling into the registry:
- http://stackoverflow.com/a/24590583/868206
- https://support.microsoft.com/en-us/kb/556009
#>
function Get-OSArchitecture {
write-verbose "Function: $($MyInvocation.MyCommand)..."
#reg Query "HKLM\Hardware\Description\System\CentralProcessor\0" | find /i "x86" > NUL && set OSARCHITECTURE=32BIT || set OSARCHITECTURE=64BIT
$OSArch = Get-WmiObject -class win32_operatingsystem -property osarchitecture | select -expand OSArchitecture
if ($OSArch -match "64") {
return "amd64"
}
elseif ($OSArch -match "32") {
return "i386"
}
else {
throw "Could not determine OS Architecture from string '$OSArch'"
}
}
function Test-AdminPrivileges {
$me = [Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()
return $me.IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
}
function Limit-TextWidth {
[cmdletbinding()]
param(
[parameter(mandatory=$true)] [string] $text,
[parameter(mandatory=$true)] [int] $width,
[int] $indentSpaces = 0
)
$width = $width -1
if ($indentSpaces -ge $width) {
throw "`$indentSpaces must be smaller than `$width"
}
$indent = " " * $indentSpaces
$output = ""
$ctr=0
foreach ($line in ($text -split "`n")) {
$ctr+=1
#write-host -foreground cyan "${ctr}: $line"
$finished = $false
while (-not $finished) {
$line = "$indent$line"
if ($line.length -gt $width) {
$output += $line.substring(0,$width)
$output += "`n"
$line = $line.substring($width)
}
else {
$output += $line
$output += "`n"
$finished = $true
}
}
if ($output[-1] -ne "`n") {
$output += "`n"
}
}
return $output
}
function Show-ErrorReport {
[cmdletbinding()]
param(
[switch] $ExitIfErrors
)
write-verbose "`$error.count = $($error.count)"
write-verbose "`$LASTEXITCODE = $LastExitCode"
if ($Host -and $Host.UI -and $Host.UI.RawUI) {
$wrapWidth = $Host.UI.RawUI.Buffersize.Width
}
else {
$wrapWidth = 9999
}
$doExit = $false
$reportString = "ERROR Report: No errors`n"
if ($error.count -or $LASTEXITCODE) {
$errorSummary = "`$LASTEXITCODE=$LastExitCode, `$Error.count=$($Error.count)"
$reportString = "ERROR Report: $errorSummary`n`n"
for ($i= $error.count -1; $i -ge 0; $i -= 1) {
write-verbose "Processing error $i"
$e = $error[$i]
$errorDetails = "PS `$Error[$i]: `n"
$indentCount = 4
# $error can contain at least 2 kinda of objects - ErrorRecord objects, and things that wrap ErrorRecord objects
# The information we need is found in the ErrorRecord objects, so unwrap them here if necessary
if ($e.ErrorRecord) {
$e = $e.ErrorRecord
}
$errorDetails += Limit-TextWidth -text $e.ToString() -width $wrapWidth -indent $indentCount
if ($errorDetails[-1] -ne "`n") { $errorDetails += "`n" }
if ($e.ScriptStackTrace) {
$errorDetails += Limit-TextWidth -text $e.ScriptStackTrace -width $wrapWidth -indent $indentCount
if ($errorDetails[-1] -ne "`n") { $errorDetails += "`n" }
}
$reportString += $errorDetails
}
if ($ExitIfErrors) {
$doExit = $true
$reportString += "Exiting with returncode 1...`n"
}
}
write-output "----`n$reportString----"
if ($doExit) {
exit 1
}
}
set-alias err Show-ErrorReport
$script:szInstallDir = "$env:ProgramFiles\7-Zip"
set-alias sevenzip "${script:szInstallDir}\7z.exe"
function Install-SevenZip {
write-verbose "Function: $($MyInvocation.MyCommand)..."
$OSArch = Get-OSArchitecture
if ($OSArch -match "i386") {
$szFilename = "7z920.msi"
}
elseif ($OSArch -match "amd64") {
$szFilename = "7z920-x64.msi"
}
else {
throw "Cannot install 7-zip for an architecture of '$OSArch'"
}
$szUrl = "http://7-zip.org/a/$szFilename"
$szDlPath = "$(Get-LabTempDir)\$szFilename"
Get-WebUrl -url $szUrl -downloadPath $szDlPath
write-verbose "Downloaded '$szUrl' to '$szDlPath', now running msiexec..."
#msiexec /qn /i "$szDlPath"
#[Diagnostics.Process]::Start("msiexec",@("/quiet","/qn","/i",$szDlPath)).WaitForExit()
#[Diagnostics.Process]::Start("msiexec", "/i","`"$szDlPath`","/q","/INSTALLDIR=`"$szInstallDir`"")).WaitForExit()
#msiexec /i "`"$sqlDlPath`"" /q "/INSTALLDIR=`"$script:szInstallDir`""
#$msiArgs = '/i "${0}" /q /INSTALLDIR="{1}"' -f $szDlPath, $szInstallDir
#$msiArgs = '/i "${0}" /qn /INSTALLDIR="{1}"' -f $szDlPath, $szInstallDir
#([Diagnostics.Process]::Start("msiexec", $msiArgs)).WaitForExit()
msiexec /qn /i "$szDlPath"
sleep 30 # Windows is bad, written by bad people who write bad software. More like softWHEREdidyougetthisideaitSUCKS amirite??
if ($LASTEXITCODE -and ($LASTEXITCODE -ne 0)) { throw "External command failed with code '$LASTEXITCODE'" }
$szExePath = get-item (gcm sevenzip | select -expand definition)
write-verbose "Installed 7-zip to: $szExePath"
}
function Install-VBoxAdditions {
[cmdletbinding()]
param(
[parameter(ParameterSetName="FromIso",mandatory=$true)] [string] $isoPath,
[parameter(ParameterSetName="FromDisc",mandatory=$true)] [switch] $fromDisc
)
if ($PsCmdlet.ParameterSetName -match "FromIso") {
write-verbose "Function: $($MyInvocation.MyCommand)..."
$isoPath = resolve-path $isoPath | select -expand Path
$vbgaPath = "$(Get-LabTempDir)\InstallVbox"
mkdir -force $vbgaPath
write-verbose "Extracting iso at '$isoPath' to directory at '$vbgaPath'..."
sevenzip x "$isoPath" "-o$vbgaPath"
if ($LASTEXITCODE -and ($LASTEXITCODE -ne 0)) { throw "External command failed with code '$LASTEXITCODE'" }
}
elseif ($PsCmdlet.ParameterSetName -match "FromDisc") {
foreach ($drive in (Get-PSDrive -PSProvider FileSystem)) {
if (test-path "$($drive.Name):\VboxWindowsAdditions.exe") {
$vbgaPath = "$($drive.Name):"
break
}
}
}
else {
throw "No such parameter set '$($psCmdlet.ParameterSetName)'"
}
if (-not "$vbgaPath") { throw "Could not find VBox Guest Additions" }
write-verbose "Installing the Oracle certificate..."
set-alias VboxCertUtil "$vbgaPath\cert\VBoxCertUtil.exe"
$oracleCert = resolve-path "$vbgaPath\cert\oracle-vbox.cer" | select -expand path
VboxCertUtil add-trusted-publisher $oracleCert --root $oracleCert
# NOTE: Checking for exit code, but this command will fail with an error if the cert is already installed
# TODO: what is the error code in that case? get it and ignore it here
if ($LASTEXITCODE -and ($LASTEXITCODE -ne 0)) { throw "External command failed with code '$LASTEXITCODE'" }
write-verbose "Installing the virtualbox additions"
set-alias VBoxWindowsAdditions "$vbgaPath\VBoxWindowsAdditions.exe"
$startTime = get-date
VBoxWindowsAdditions /with_wddm /S # returns IMMEDIATELY
while (get-process -Name VBoxWindowsAdditions*) { write-verbose 'Waiting for VBox install to finish...'; sleep 1; }
$endTime = get-date
write-verbose "Running the VboxWindowsAdditions installer took $($endTime - $startTime | select -expand seconds) seconds"
}
function Disable-AutoAdminLogon {
write-verbose "Function: $($MyInvocation.MyCommand)..."
set-itemproperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" -Name AutoAdminLogon -Value 0
}
function Enable-RDP {
write-verbose "Function: $($MyInvocation.MyCommand)..."
netsh advfirewall firewall add rule name="Open Port 3389" dir=in action=allow protocol=TCP localport=3389
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f
}
# TODO: only works on x86
function Install-CompiledDotNetAssemblies {
write-verbose "Function: $($MyInvocation.MyCommand)..."
# http://support.microsoft.com/kb/2570538
# http://robrelyea.wordpress.com/2007/07/13/may-be-helpful-ngen-exe-executequeueditems/
set-alias ngen32 "${env:WinDir}\microsoft.net\framework\v4.0.30319\ngen.exe"
ngen32 update /force /queue
ngen32 executequeueditems
if ((Get-OSArchitecture) -match "amd64") {
set-alias ngen64 "${env:WinDir}\microsoft.net\framework64\v4.0.30319\ngen.exe"
ngen64 update /force /queue
ngen64 executequeueditems
}
}
function Compress-WindowsInstall {
write-verbose "Function: $($MyInvocation.MyCommand)..."
$temp = Get-LabTempDir
$OSArch = Get-OSArchitecture
if ($OSArch -match "i386") { $udfArch = "i386" }
elseif ($OSArch -match "amd64") { $udfArch = "amd64" }
else {throw "Cannot compact for architecture '$OSArch'"}
$udfFilename = "ultradefrag-portable-6.1.0.bin.$udfArch.zip"
$udfUrl = "http://downloads.sourceforge.net/project/ultradefrag/stable-release/6.1.0/$udfFilename"
$udfZipPath = "$temp\$udfFilename"
Get-WebUrl -url $udfUrl -downloadPath $udfZipPath
sevenzip x "$udfZipPath" "-o$temp"
set-alias udefrag "$temp\ultradefrag-portable-6.1.0.$udfArch\udefrag.exe"
$sdZipPath = "$temp\SDelete.zip"
Get-WebUrl -url http://download.sysinternals.com/files/SDelete.zip -downloadPath $sdZipPath
sevenzip x "$sdZipPath" "-o$temp"
set-alias sdelete "$temp\SDelete.exe"
stop-service wuauserv
rm -recurse -force ${env:WinDir}\SoftwareDistribution\Download
start-service wuauserv
udefrag --optimize --repeat "$env:SystemDrive"
reg.exe ADD HKCU\Software\Sysinternals\SDelete /v EulaAccepted /t REG_DWORD /d 1 /f
sdelete -q -z "$env:SystemDrive"
}
function Disable-WindowsUpdates {
if (-not (Test-AdminPrivileges)) {
throw "Cannot run without administrator privileges"
}
$Updates = (New-Object -ComObject "Microsoft.Update.AutoUpdate").Settings
if ($Updates.ReadOnly) {
throw "Cannot update Windows Update settings due to GPO restrictions."
}
$Updates.NotificationLevel = 1 #Disabled
$Updates.Save()
$Updates.Refresh()
}
function Enable-MicrosoftUpdate {
stop-service wuauserv
$auKey = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update"
Set-ItemProperty -path $auKey -name EnableFeaturedSoftware -value 1
Set-ItemProperty -path $auKey -name IncludeRecommendedUpdates -value 1
$ServiceManager = New-Object -ComObject "Microsoft.Update.ServiceManager"
$ServiceManager.AddService2("7971f918-a847-4430-9279-4a52d1efe18d",7,"")
start-service wuauserv
}
function Install-Chocolatey {
$chocoExePath = "${env:ProgramData}\Chocolatey\bin"
if ($($env:Path).ToLower().Contains($($chocoExePath).ToLower())) {
write-verbose "Chocolatey already in path, exiting..."
return
}
# Add to system PATH
$systemPath = [Environment]::GetEnvironmentVariable('Path', [System.EnvironmentVariableTarget]::Machine)
$systemPath += ";$chocoExePath"
[Environment]::SetEnvironmentVariable("PATH", $systemPath, [System.EnvironmentVariableTarget]::Machine)
# Update local process' path
$env:Path = $systemPath
$userPath = [Environment]::GetEnvironmentVariable('Path', [System.EnvironmentVariableTarget]::User)
if ($userPath) { $env:Path += ";$userPath" }
# Run the installer
iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))
}
<#
.description
Formerly:
- reg.exe ADD HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced\ /v HideFileExt /t REG_DWORD /d 0 /f
- reg.exe ADD HKCU\Console /v QuickEdit /t REG_DWORD /d 1 /f
#>
function Set-UserOptions {
[cmdletbinding()] param(
[switch] $ShowHiddenFiles,
[switch] $ShowSystemFiles,
[switch] $ShowFileExtensions,
[switch] $ShowStatusBar,
[switch] $DisableSharingWizard,
[switch] $EnablePSOnWinX,
[switch] $EnableQuickEdit
)
$explorerAdvancedKey = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced'
if ($ShowHiddenFiles) { Set-ItemProperty -path $explorerAdvancedKey -name Hidden -value 1 }
if ($ShowSystemFiles) { Set-ItemProperty -path $explorerAdvancedKey -name ShowSuperHidden -value 1 }
if ($ShowFileExtensions) { Set-ItemProperty -path $explorerAdvancedKey -name HideFileExt -value 0 }
if ($ShowStatusBar) { Set-ItemProperty -path $explorerAdvancedKey -name ShowStatusBar -value 1 }
if ($DisableSharingWizard) { Set-ItemProperty -path $explorerAdvancedKey -name SharingWizardOn -value 0 }
if ($EnablePSOnWinX) { Set-ItemProperty -path $explorerAdvancedKey -name DontUsePowerShellOnWinX -value 0 }
$consoleKey = "HKCU:\Console"
if ($EnableQuickEdit) { Set-ItemProperty -path $consoleKey -name QuickEdit -value 1 }
}
# TODO: wtfwtfwtfwtfwtfwtfwtfwtfwtf no
function Install-VagrantSshKey {
write-verbose "Function: $($MyInvocation.MyCommand)..."
$keyUrl = "https://raw.githubusercontent.com/mitchellh/vagrant/master/keys/vagrant.pub"
$authkeys = 'C:\Users\vagrant\.ssh\authorized_keys'
Get-WebUrl -url $keyUrl -downloadPath $authKeys
}
$exAlias = @("sevenzip")
$exFunction = @(
"Get-OSArchitecture"
"Get-LabTempDir"
"Install-SevenZip"
"Install-VBoxAdditions"
)
export-modulemember -alias * -function *

@ -1,10 +0,0 @@
if not exist "C:\Windows\Temp\puppet.msi" (
powershell -Command "(New-Object System.Net.WebClient).DownloadFile('http://pm.puppetlabs.com/puppet-enterprise/3.0.1/puppet-enterprise-3.0.1.msi', 'C:\Windows\Temp\puppet.msi')" <NUL
)
:: http://docs.puppetlabs.com/pe/latest/install_windows.html
msiexec /qn /i C:\Windows\Temp\puppet.msi /log C:\Windows\Temp\puppet.log
<nul set /p ".=;C:\Program Files (x86)\Puppet Labs\Puppet Enterprise\bin" >> C:\Windows\Temp\PATH
set /p PATH=<C:\Windows\Temp\PATH
setx PATH "%PATH%" /m

@ -1,10 +0,0 @@
if not exist "C:\Windows\Temp\puppet.msi" (
powershell -Command "(New-Object System.Net.WebClient).DownloadFile('http://downloads.puppetlabs.com/windows/puppet-3.6.2.msi', 'C:\Windows\Temp\puppet.msi')" <NUL
)
:: http://docs.puppetlabs.com/pe/latest/install_windows.html
msiexec /qn /i C:\Windows\Temp\puppet.msi /log C:\Windows\Temp\puppet.log
<nul set /p ".=;C:\Program Files (x86)\Puppet Labs\Puppet\bin" >> C:\Windows\Temp\PATH
set /p PATH=<C:\Windows\Temp\PATH
setx PATH "%PATH%" /m

@ -1,19 +0,0 @@
rem install rsync
if not exist "C:\Windows\Temp\7z920-x64.msi" (
powershell -Command "(New-Object System.Net.WebClient).DownloadFile('http://www.7-zip.org/a/7z920-x64.msi', 'C:\Windows\Temp\7z920-x64.msi')" <NUL
)
msiexec /qb /i C:\Windows\Temp\7z920-x64.msi
pushd C:\Windows\Temp
powershell -Command "(New-Object System.Net.WebClient).DownloadFile('http://mirrors.kernel.org/sourceware/cygwin/x86_64/release/rsync/rsync-3.1.0-1.tar.xz', 'C:\Windows\Temp\rsync-3.1.0-1.tar.xz')" <NUL
cmd /c ""C:\Program Files\7-Zip\7z.exe" x rsync-3.1.0-1.tar.xz"
cmd /c ""C:\Program Files\7-Zip\7z.exe" x rsync-3.1.0-1.tar"
copy /Y usr\bin\rsync.exe "C:\Program Files\OpenSSH\bin\rsync.exe"
rmdir /s /q usr
del rsync-3.1.0-1.tar
popd
msiexec /qb /x C:\Windows\Temp\7z920-x64.msi
rem make symlink for c:/vagrant share
mklink /D "C:\Program Files\OpenSSH\vagrant" "C:\vagrant"

@ -1,11 +0,0 @@
if not exist "C:\Windows\Temp\salt64.exe" (
powershell -Command "(New-Object System.Net.WebClient).DownloadFile('https://docs.saltstack.com/downloads/Salt-Minion-2014.1.3-1-AMD64-Setup.exe', 'C:\Windows\Temp\salt64.exe')" <NUL
)
:: http://docs.saltstack.com/en/latest/topics/installation/windows.html
c:\windows\temp\salt64.exe /S
:: /master=<yoursaltmaster> /minion-name=<thisminionname>
<nul set /p ".=;C:\salt" >> C:\Windows\Temp\PATH
set /p PATH=<C:\Windows\Temp\PATH
setx PATH "%PATH%" /m

@ -1,6 +0,0 @@
:: vagrant public key
if exist a:\vagrant.pub (
copy a:\vagrant.pub C:\Users\vagrant\.ssh\authorized_keys
) else (
powershell -Command "(New-Object System.Net.WebClient).DownloadFile('https://raw.githubusercontent.com/mitchellh/vagrant/master/keys/vagrant.pub', 'C:\Users\vagrant\.ssh\authorized_keys')" <NUL
)

@ -1,45 +0,0 @@
if "%PACKER_BUILDER_TYPE%" equ "vmware-iso" goto :vmware
if "%PACKER_BUILDER_TYPE%" equ "virtualbox-iso" goto :virtualbox
if "%PACKER_BUILDER_TYPE%" equ "parallels-iso" goto :parallels
goto :done
:vmware
if exist "C:\Users\vagrant\windows.iso" (
move /Y C:\Users\vagrant\windows.iso C:\Windows\Temp
)
if not exist "C:\Windows\Temp\windows.iso" (
powershell -Command "(New-Object System.Net.WebClient).DownloadFile('http://softwareupdate.vmware.com/cds/vmw-desktop/ws/11.1.2/2780323/windows/packages/tools-windows-9.9.3.exe.tar', 'C:\Windows\Temp\vmware-tools.exe.tar')" <NUL
cmd /c ""C:\Program Files\7-Zip\7z.exe" x C:\Windows\Temp\vmware-tools.exe.tar -oC:\Windows\Temp"
FOR /r "C:\Windows\Temp" %%a in (tools-windows-*.exe) DO REN "%%~a" "tools-windows.exe"
cmd /c C:\Windows\Temp\tools-windows
move /Y "C:\Program Files (x86)\VMware\tools-windows\windows.iso" C:\Windows\Temp
rd /S /Q "C:\Program Files (x86)\VMWare"
)
cmd /c ""C:\Program Files\7-Zip\7z.exe" x "C:\Windows\Temp\windows.iso" -oC:\Windows\Temp\VMWare"
cmd /c C:\Windows\Temp\VMWare\setup.exe /S /v"/qn REBOOT=R\"
goto :done
:virtualbox
:: There needs to be Oracle CA (Certificate Authority) certificates installed in order
:: to prevent user intervention popups which will undermine a silent installation.
cmd /c certutil -addstore -f "TrustedPublisher" A:\oracle-cert.cer
move /Y C:\Users\vagrant\VBoxGuestAdditions.iso C:\Windows\Temp
cmd /c ""C:\Program Files\7-Zip\7z.exe" x C:\Windows\Temp\VBoxGuestAdditions.iso -oC:\Windows\Temp\virtualbox"
cmd /c C:\Windows\Temp\virtualbox\VBoxWindowsAdditions.exe /S
goto :done
:parallels
if exist "C:\Users\vagrant\prl-tools-win.iso" (
move /Y C:\Users\vagrant\prl-tools-win.iso C:\Windows\Temp
cmd /C "C:\Program Files\7-Zip\7z.exe" x C:\Windows\Temp\prl-tools-win.iso -oC:\Windows\Temp\parallels
cmd /C C:\Windows\Temp\parallels\PTAgent.exe /install_silent
rd /S /Q "c:\Windows\Temp\parallels"
)
:done

@ -5,4 +5,13 @@
- test `lab2 -action VagrantUp -baseConfigName windows_81_x86 -tag PreLunchTest` tomorrow afternoon - will it have 89 days remaining? or 90? basically, was it activated at boot or nah?
- need to audit **all** of the scripts ../scripts actually
- it seems like the vbox tools aren't getting installed? why not?
- enable clipboard and drag&drop in my Vagrantfile - though NOT for throwaway VMs that might be insecure!
- enable clipboard and drag&drop in my Vagrantfile - though NOT for throwaway VMs that might be insecure!
- Seems like I'm not actually defragging it in my compact.bat?
- Fucking vbox guest tools aren't installing, god I hate batch scripts
Dumb shit I figured out about how fucking bad Packer is while I got to do this
- The shell, windows-shell, and powershell provisioners are VERY finicky. I canNOT make them work reliably
- Best thing to do is upload a script with a "file" provisioner and run it with a "windows-shell" provisioner that has one inline command
- ps you can't upload directories for some reason. just individual files. one. by. fucking. one.

@ -202,26 +202,7 @@
<Order>15</Order>
<RequiresUserInput>true</RequiresUserInput>
</SynchronousCommand>
<SynchronousCommand wcm:action="add">
<CommandLine>%SystemRoot%\System32\reg.exe ADD HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced\ /v HideFileExt /t REG_DWORD /d 0 /f</CommandLine>
<Order>16</Order>
<Description>Show file extensions in Explorer</Description>
</SynchronousCommand>
<SynchronousCommand wcm:action="add">
<CommandLine>%SystemRoot%\System32\reg.exe ADD HKCU\Console /v QuickEdit /t REG_DWORD /d 1 /f</CommandLine>
<Order>17</Order>
<Description>Enable QuickEdit mode</Description>
</SynchronousCommand>
<SynchronousCommand wcm:action="add">
<CommandLine>%SystemRoot%\System32\reg.exe ADD HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced\ /v Start_ShowRun /t REG_DWORD /d 1 /f</CommandLine>
<Order>18</Order>
<Description>Show Run command in Start Menu</Description>
</SynchronousCommand>
<SynchronousCommand wcm:action="add">
<CommandLine>%SystemRoot%\System32\reg.exe ADD HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced\ /v StartMenuAdminTools /t REG_DWORD /d 1 /f</CommandLine>
<Order>19</Order>
<Description>Show Administrative Tools in Start Menu</Description>
</SynchronousCommand>
<SynchronousCommand wcm:action="add">
<CommandLine>%SystemRoot%\System32\reg.exe ADD HKLM\SYSTEM\CurrentControlSet\Control\Power\ /v HibernateFileSizePercent /t REG_DWORD /d 0 /f</CommandLine>
<Order>20</Order>
@ -232,18 +213,22 @@
<Order>21</Order>
<Description>Disable Hibernation Mode</Description>
</SynchronousCommand>
<SynchronousCommand wcm:action="add">
<CommandLine>cmd.exe /c wmic useraccount where "name='vagrant'" set PasswordExpires=FALSE</CommandLine>
<Order>22</Order>
<Description>Disable password expiration for vagrant user</Description>
</SynchronousCommand>
<!-- WITHOUT WINDOWS UPDATES -->
<!--
<SynchronousCommand wcm:action="add">
<CommandLine>cmd.exe /c C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -File a:\openssh.ps1 -AutoStart</CommandLine>
<Description>Install OpenSSH</Description>
<Order>99</Order>
<RequiresUserInput>true</RequiresUserInput>
</SynchronousCommand>
-->
<!-- END WITHOUT WINDOWS UPDATES -->
<!-- WITH WINDOWS UPDATES -->
<!--

@ -0,0 +1,6 @@
set POWERSHELL=%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe
set POSTINSTALLSCRIPT=C:\PackerTemp\postinstall\postinstall.ps1
dir C:\
dir C:\PackerTemp
dir C:\PackerTemp\postinstall
%POWERSHELL% -NoLogo -NoProfile -NonInteractive -File %POSTINSTALLSCRIPT%

@ -19,7 +19,7 @@ Vagrant.configure("2") do |config|
config.vm.network :forwarded_port, guest: 22, host: 2222, id: "ssh", auto_correct: true
config.vm.provider :virtualbox do |v, override|
v.gui = true
#v.gui = true
v.customize ["modifyvm", :id, "--memory", 2048]
v.customize ["modifyvm", :id, "--cpus", 2]
v.customize ["setextradata", "global", "GUI/SuppressMessages", "all" ]

@ -10,55 +10,52 @@
"iso_checksum": "4ddd0881779e89d197cb12c684adf47fd5d9e540",
"headless": true,
"boot_wait": "2m",
"ssh_username": "vagrant",
"ssh_password": "vagrant",
"ssh_wait_timeout": "4h",
"communicator": "winrm",
"winrm_username": "vagrant",
"winrm_password": "vagrant",
"winrm_timeout": "2h",
"shutdown_command": "shutdown /s /t 10 /f /d p:4:1 /c \"Packer Shutdown\"",
"guest_os_type": "Windows81",
"disk_size": 61440,
"guest_additions_mode": "attach",
"floppy_files": [
"./Autounattend.xml",
"../scripts/microsoft-updates.bat",
"../scripts/win-updates.ps1",
"../scripts/openssh.ps1",
"../scripts/oracle-cert.cer"
"../scripts/win-updates.ps1"
],
"vboxmanage": [
[
"modifyvm",
"{{.Name}}",
"--memory",
"2048"
],
[
"modifyvm",
"{{.Name}}",
"--cpus",
"2"
]
[ "modifyvm", "{{.Name}}", "--memory", "2048" ],
[ "modifyvm", "{{.Name}}", "--cpus", "2" ]
]
}
],
"provisioners": [
{
"type": "shell",
"remote_path": "/tmp/script.bat",
"execute_command": "{{.Vars}} cmd /c C:/Windows/Temp/script.bat",
"scripts": [
"../scripts/install-7zip.bat",
"../scripts/vm-guest-tools.bat",
"../scripts/vagrant-ssh.bat",
"../scripts/disable-auto-logon.bat",
"../scripts/enable-rdp.bat",
"../scripts/compile-dotnet-assemblies.bat",
"../scripts/compact.bat"
"type": "windows-shell",
"inline": [
"cmd /c md C:\\PackerTemp\\PostInstall"
]
},
{
"type": "file",
"source": "../scripts/postinstall/wintriallab-postinstall.psm1",
"destination": "C:\\PackerTemp\\PostInstall\\wintriallab-postinstall.psm1",
"direction": "upload"
},
{
"type": "file",
"source": "../scripts/postinstall/postinstall.ps1",
"destination": "C:\\PackerTemp\\PostInstall\\postinstall.ps1",
"direction": "upload"
},
{
"type": "shell",
"inline": [
"rm -rf /tmp/*"
]
"type": "powershell",
"inline": ["C:\\PackerTemp\\PostInstall\\postinstall.ps1 -Verbose"]
},
{
"type": "windows-shell",
"inline": ["rmdir /S /Q C:\\PackerTemp"]
}
],
"post-processors": [

Loading…
Cancel
Save