Guest User

Untitled

a guest
Apr 24th, 2018
312
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JSON 13.17 KB | None | 0 0
  1. 2012.json:
  2.  
  3. {
  4.     "variables": {
  5.         "source_ami": "{{env `AMI`}}",
  6.         "ami_users": "{{env `ACCOUNT`}}",
  7.         "snapshot_users": "{{env `ACCOUNT`}}"
  8.     },
  9.     "builders": [{
  10.         "type": "amazon-ebs",
  11.         "region": "us-east-1",
  12.         "source_ami": "{{user `source_ami`}}",
  13.         "instance_type": "m3.medium",
  14.         "user_data_file": "./ec2-userdata.ps1",
  15.         "iam_instance_profile": "Packer",
  16.         "ami_users": "{{user `ami_users`}}",
  17.         "snapshot_users": "{{user `snapshot_users`}}",
  18.         "ami_name": "2012 R2 TEST {{timestamp}}",
  19.         "communicator": "winrm",
  20.         "winrm_username": "Administrator",
  21.         "winrm_use_ssl": true,
  22.         "winrm_insecure": true
  23.     }],
  24.     "provisioners": [
  25.         {
  26.     "type": "powershell",
  27.     "environment_vars": "WINRMPASS={{.WinRMPassword}}",
  28.     "elevated_user": "Administrator",
  29.     "elevated_password": "{{.WinRMPassword}}",
  30.     "script": "install-updates-2012.ps1"
  31. }
  32.     ]
  33.     }
  34.  
  35.  
  36. ec2-userdata:
  37. <powershell>
  38. write-output "Running User Data Script"
  39. write-host "(host) Running User Data Script"
  40. Set-ExecutionPolicy Unrestricted -Scope LocalMachine -Force -ErrorAction Ignore
  41. # Don't set this before Set-ExecutionPolicy as it throws an error
  42. $ErrorActionPreference = "stop"
  43. # Remove HTTP listener
  44. Remove-Item -Path WSMan:\Localhost\listener\listener* -Recurse
  45. $Cert = New-SelfSignedCertificate -CertstoreLocation Cert:\LocalMachine\My -DnsName "packer"
  46. New-Item -Path WSMan:\LocalHost\Listener -Transport HTTPS -Address * -CertificateThumbPrint $Cert.Thumbprint -Force
  47. # WinRM
  48. write-output "Setting up WinRM"
  49. write-host "(host) setting up WinRM"
  50. cmd.exe /c winrm quickconfig -q
  51. cmd.exe /c winrm set "winrm/config" '@{MaxTimeoutms="1800000"}'
  52. cmd.exe /c winrm set "winrm/config/winrs" '@{MaxMemoryPerShellMB="1024"}'
  53. cmd.exe /c winrm set "winrm/config/service" '@{AllowUnencrypted="true"}'
  54. cmd.exe /c winrm set "winrm/config/client" '@{AllowUnencrypted="true"}'
  55. cmd.exe /c winrm set "winrm/config/service/auth" '@{Basic="true"}'
  56. cmd.exe /c winrm set "winrm/config/client/auth" '@{Basic="true"}'
  57. cmd.exe /c winrm set "winrm/config/service/auth" '@{CredSSP="true"}'
  58. cmd.exe /c winrm set "winrm/config/listener?Address=*+Transport=HTTPS" "@{Port=`"5986`";Hostname=`"packer`";CertificateThumbprint=`"$($Cert.Thumbprint)`"}"
  59. cmd.exe /c netsh advfirewall firewall set rule group="remote administration" new enable=yes
  60. cmd.exe /c netsh firewall add portopening TCP 5986 "Port 5986"
  61. cmd.exe /c net stop winrm
  62. cmd.exe /c sc config winrm start= auto
  63. cmd.exe /c net start winrm
  64. </powershell>
  65.  
  66. install-updates-2012.ps1
  67. param($global:RestartRequired=0,
  68.        $global:MoreUpdates=0,
  69.        $global:MaxCycles=5,
  70.        $MaxUpdatesPerCycle=500)
  71.  
  72. $Logfile = "C:\Windows\Temp\WindowsUpdate.log"
  73.  
  74. function LogWrite {
  75.   Param ([string]$logstring)
  76.   $now = Get-Date -format s
  77.   Add-Content $Logfile -value "$now $logstring"
  78.   Write-Host $logstring
  79. }
  80.  
  81. function Check-ContinueRestartOrEnd() {
  82.    $RegistryKey = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run"
  83.    $RegistryEntry = "InstallWindowsUpdates"
  84.    switch ($global:RestartRequired) {
  85.        0 {
  86.            $prop = (Get-ItemProperty $RegistryKey).$RegistryEntry
  87.            if ($prop) {
  88.                LogWrite "Restart Registry Entry Exists - Removing It"
  89.                Remove-ItemProperty -Path $RegistryKey -Name $RegistryEntry -ErrorAction SilentlyContinue
  90.            }
  91.  
  92.            LogWrite "No Restart Required"
  93.            Check-WindowsUpdates
  94.  
  95.            if (($global:MoreUpdates -eq 1) -and ($script:Cycles -le $global:MaxCycles)) {
  96.                Install-WindowsUpdates
  97.            } elseif ($script:Cycles -gt $global:MaxCycles) {
  98.                LogWrite "Exceeded Cycle Count - Stopping"
  99.            } else {
  100.                LogWrite "Done Installing Windows Updates"
  101.            }
  102.        }
  103.        1 {
  104.            $prop = (Get-ItemProperty $RegistryKey).$RegistryEntry
  105.            if (-not $prop) {
  106.                LogWrite "Restart Registry Entry Does Not Exist - Creating It"
  107.                Set-ItemProperty -Path $RegistryKey -Name $RegistryEntry -Value "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -File $($script:ScriptPath) -MaxUpdatesPerCycle $($MaxUpdatesPerCycle)"
  108.            } else {
  109.                LogWrite "Restart Registry Entry Exists Already"
  110.            }
  111.  
  112.            LogWrite "Restart Required - Restarting..."
  113.            Restart-Computer
  114.        }
  115.        default {
  116.            LogWrite "Unsure If A Restart Is Required"
  117.            break
  118.        }
  119.    }
  120. }
  121.  
  122. function Install-WindowsUpdates() {
  123.    $script:Cycles++
  124.    LogWrite "Evaluating Available Updates with limit of $($MaxUpdatesPerCycle):"
  125.    $UpdatesToDownload = New-Object -ComObject 'Microsoft.Update.UpdateColl'
  126.    $script:i = 0;
  127.    $CurrentUpdates = $SearchResult.Updates
  128.    while($script:i -lt $CurrentUpdates.Count -and $script:CycleUpdateCount -lt $MaxUpdatesPerCycle) {
  129.        $Update = $CurrentUpdates.Item($script:i)
  130.        if (($Update -ne $null) -and (!$Update.IsDownloaded)) {
  131.            [bool]$addThisUpdate = $false
  132.            if ($Update.InstallationBehavior.CanRequestUserInput) {
  133.                LogWrite "> Skipping: $($Update.Title) because it requires user input"
  134.            } else {
  135.                if (!($Update.EulaAccepted)) {
  136.                    LogWrite "> Note: $($Update.Title) has a license agreement that must be accepted. Accepting the license."
  137.                    $Update.AcceptEula()
  138.                    [bool]$addThisUpdate = $true
  139.                    $script:CycleUpdateCount++
  140.                } else {
  141.                    [bool]$addThisUpdate = $true
  142.                    $script:CycleUpdateCount++
  143.                }
  144.            }
  145.  
  146.            if ([bool]$addThisUpdate) {
  147.                LogWrite "Adding: $($Update.Title)"
  148.                $UpdatesToDownload.Add($Update) |Out-Null
  149.            }
  150.        }
  151.        $script:i++
  152.    }
  153.  
  154.    if ($UpdatesToDownload.Count -eq 0) {
  155.        LogWrite "No Updates To Download..."
  156.    } else {
  157.        LogWrite 'Downloading Updates...'
  158.        $ok = 0;
  159.        while (! $ok) {
  160.            try {
  161.                $Downloader = $UpdateSession.CreateUpdateDownloader()
  162.                $Downloader.Updates = $UpdatesToDownload
  163.                $Downloader.Download()
  164.                $ok = 1;
  165.            } catch {
  166.                LogWrite $_.Exception | Format-List -force
  167.                LogWrite "Error downloading updates. Retrying in 30s."
  168.                $script:attempts = $script:attempts + 1
  169.                Start-Sleep -s 30
  170.            }
  171.        }
  172.    }
  173.  
  174.    $UpdatesToInstall = New-Object -ComObject 'Microsoft.Update.UpdateColl'
  175.    [bool]$rebootMayBeRequired = $false
  176.    LogWrite 'The following updates are downloaded and ready to be installed:'
  177.    foreach ($Update in $SearchResult.Updates) {
  178.        if (($Update.IsDownloaded)) {
  179.            LogWrite "> $($Update.Title)"
  180.            $UpdatesToInstall.Add($Update) |Out-Null
  181.  
  182.            if ($Update.InstallationBehavior.RebootBehavior -gt 0){
  183.                [bool]$rebootMayBeRequired = $true
  184.            }
  185.        }
  186.    }
  187.  
  188.    if ($UpdatesToInstall.Count -eq 0) {
  189.        LogWrite 'No updates available to install...'
  190.        $global:MoreUpdates=0
  191.        $global:RestartRequired=0
  192.        break
  193.    }
  194.  
  195.    if ($rebootMayBeRequired) {
  196.        LogWrite 'These updates may require a reboot'
  197.        $global:RestartRequired=1
  198.    }
  199.  
  200.    LogWrite 'Installing updates...'
  201.  
  202.    $Installer = $script:UpdateSession.CreateUpdateInstaller()
  203.    $Installer.Updates = $UpdatesToInstall
  204.    $InstallationResult = $Installer.Install()
  205.  
  206.    LogWrite "Installation Result: $($InstallationResult.ResultCode)"
  207.    LogWrite "Reboot Required: $($InstallationResult.RebootRequired)"
  208.    LogWrite 'Listing of updates installed and individual installation results:'
  209.    if ($InstallationResult.RebootRequired) {
  210.        $global:RestartRequired=1
  211.    } else {
  212.        $global:RestartRequired=0
  213.    }
  214.  
  215.    for($i=0; $i -lt $UpdatesToInstall.Count; $i++) {
  216.        New-Object -TypeName PSObject -Property @{
  217.            Title = $UpdatesToInstall.Item($i).Title
  218.            Result = $InstallationResult.GetUpdateResult($i).ResultCode
  219.        }
  220.        LogWrite "Item: $($UpdatesToInstall.Item($i).Title)"
  221.        LogWrite "Result: $($InstallationResult.GetUpdateResult($i).ResultCode)"
  222.    }
  223.  
  224.    Check-ContinueRestartOrEnd
  225. }
  226.  
  227. function Check-WindowsUpdates() {
  228.    LogWrite "Checking For Windows Updates"
  229.    $Username = $env:USERDOMAIN + "\" + $env:USERNAME
  230.  
  231.    New-EventLog -Source $ScriptName -LogName 'Windows Powershell' -ErrorAction SilentlyContinue
  232.  
  233.    $Message = "Script: " + $ScriptPath + "`nScript User: " + $Username + "`nStarted: " + (Get-Date).toString()
  234.  
  235.    Write-EventLog -LogName 'Windows Powershell' -Source $ScriptName -EventID "104" -EntryType "Information" -Message $Message
  236.    LogWrite $Message
  237.  
  238.    $script:UpdateSearcher = $script:UpdateSession.CreateUpdateSearcher()
  239.    $script:successful = $FALSE
  240.    $script:attempts = 0
  241.    $script:maxAttempts = 12
  242.    while(-not $script:successful -and $script:attempts -lt $script:maxAttempts) {
  243.        try {
  244.            $script:SearchResult = $script:UpdateSearcher.Search("IsInstalled=0 and Type='Software' and IsHidden=0")
  245.            $script:successful = $TRUE
  246.        } catch {
  247.            LogWrite $_.Exception | Format-List -force
  248.            LogWrite "Search call to UpdateSearcher was unsuccessful. Retrying in 10s."
  249.            $script:attempts = $script:attempts + 1
  250.            Start-Sleep -s 10
  251.        }
  252.    }
  253.  
  254.    if ($SearchResult.Updates.Count -ne 0) {
  255.        $Message = "There are " + $SearchResult.Updates.Count + " more updates."
  256.        LogWrite $Message
  257.        try {
  258.            for($i=0; $i -lt $script:SearchResult.Updates.Count; $i++) {
  259.              LogWrite $script:SearchResult.Updates.Item($i).Title
  260.              LogWrite $script:SearchResult.Updates.Item($i).Description
  261.              LogWrite $script:SearchResult.Updates.Item($i).RebootRequired
  262.              LogWrite $script:SearchResult.Updates.Item($i).EulaAccepted
  263.          }
  264.            $global:MoreUpdates=1
  265.        } catch {
  266.            LogWrite $_.Exception | Format-List -force
  267.            LogWrite "Showing SearchResult was unsuccessful. Rebooting."
  268.            $global:RestartRequired=1
  269.            $global:MoreUpdates=0
  270.            Check-ContinueRestartOrEnd
  271.            LogWrite "Show never happen to see this text!"
  272.            Restart-Computer
  273.        }
  274.    } else {
  275.        LogWrite 'There are no applicable updates'
  276.        $global:RestartRequired=0
  277.        $global:MoreUpdates=0
  278.    }
  279. }
  280.  
  281. $script:ScriptName = $MyInvocation.MyCommand.ToString()
  282. $script:ScriptPath = $MyInvocation.MyCommand.Path
  283. $script:UpdateSession = New-Object -ComObject 'Microsoft.Update.Session'
  284. $script:UpdateSession.ClientApplicationID = 'Packer Windows Update Installer'
  285. $script:UpdateSearcher = $script:UpdateSession.CreateUpdateSearcher()
  286. $script:SearchResult = New-Object -ComObject 'Microsoft.Update.UpdateColl'
  287. $script:Cycles = 0
  288. $script:CycleUpdateCount = 0
  289.  
  290. Check-WindowsUpdates
  291. if ($global:MoreUpdates -eq 1) {
  292.    Install-WindowsUpdates
  293. } else {
  294.    Check-ContinueRestartOrEnd
  295. }
  296.  
  297.  
  298.  
  299.  
  300. ERROR:
  301.  
  302. WinRM connected.
  303. ==> amazon-ebs: Connected to WinRM!
  304. ==> amazon-ebs: Provisioning with Powershell...
  305. ==> amazon-ebs: Provisioning with powershell script: install-updates-2012.ps1
  306.    amazon-ebs: Exception calling "RegisterTaskDefinition" with "7" argument(s): "The user
  307.    amazon-ebs: name or password is incorrect. (Exception from HRESULT: 0x8007052E)"
  308.    amazon-ebs: At C:\Users\Administrator\AppData\Local\Temp\packer-elevated-shell-5adf6c79-801
  309.    amazon-ebs: 1-c45a-030c-a5d7a7713f6c.ps1:49 char:1
  310.    amazon-ebs: + $f.RegisterTaskDefinition($name, $t, 6, "Administrator", "<no value>", 1,
  311.    amazon-ebs: $null) ...
  312.    amazon-ebs: + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  313.    amazon-ebs: ~~~
  314.    amazon-ebs:     + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
  315.    amazon-ebs:     + FullyQualifiedErrorId : ComMethodTargetInvocation
  316.    amazon-ebs:
  317.    amazon-ebs: Exception calling "GetTask" with "1" argument(s): "The system cannot find the
  318.    amazon-ebs: file specified. (Exception from HRESULT: 0x80070002)"
  319.    amazon-ebs: At C:\Users\Administrator\AppData\Local\Temp\packer-elevated-shell-5adf6c79-801
  320.    amazon-ebs: 1-c45a-030c-a5d7a7713f6c.ps1:50 char:1
  321.    amazon-ebs: + $t = $f.GetTask("\$name")
  322.    amazon-ebs: + ~~~~~~~~~~~~~~~~~~~~~~~~~
  323.    amazon-ebs:     + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
  324.    amazon-ebs:     + FullyQualifiedErrorId : ComMethodTargetInvocation
  325.    amazon-ebs:
  326.    amazon-ebs: Method invocation failed because [System.__ComObject] does not contain a
  327.    amazon-ebs: method named 'Run'.
  328.    amazon-ebs: At C:\Users\Administrator\AppData\Local\Temp\packer-elevated-shell-5adf6c79-801
  329.    amazon-ebs: 1-c45a-030c-a5d7a7713f6c.ps1:51 char:1
  330.    amazon-ebs: + $t.Run($null) | Out-Null
  331.    amazon-ebs: + ~~~~~~~~~~~~~~~~~~~~~~~~
  332.    amazon-ebs:     + CategoryInfo          : InvalidOperation: (Run:String) [], RuntimeExcept
  333.    amazon-ebs:    ion
  334.    amazon-ebs:     + FullyQualifiedErrorId : MethodNotFound
  335.    amazon-ebs:
Add Comment
Please, Sign In to add comment