IMAGE_STATE_UNDEPLOYABLE with Packer and Azure
Steve Jennings
by Steve Jennings

Ever run into IMAGE_STATE_UNDEPLOYABLE when running Packer against Azure?

…And it keeps going and going?

The issue here is actually with sysprep and not packer. Surprise, surprise. This error occurs because Sysprep fails to actually set the imagestate. And is an issue with the Azure Agent. See this post for information on the Azure Agent.

So our solution is in the provisioners block and add the following to the provisioners array with the powershell code:

"Set-Service RdAgent -StartupType Disabled", # Add this line, disables the VM agent (WaAppAgent)
"Set-Service WindowsAzureTelemetryService -StartupType Disabled", # Add this line, disables the Windows Azure Agent Telemetry Service
"Set-Service WindowsAzureGuestAgent -StartupType Disabled", # Add this line, disables the Windows Azure Guest Agent
"Remove-ItemProperty -Path 'HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Setup\\SysPrepExternal\\Generalize' -Name '*'" # Add this line, clears any Sysprep entries prior to running the actual sysprep command in our inline code 

Final result sample:

    "provisioners": [
        {
        "type": "powershell",
        "inline": [
            "(Invoke-WebRequest -Uri 'https://raw.githubusercontent.com/ansible/ansible/devel/examples/scripts/ConfigureRemotingForAnsible.ps1' -UseBasicParsing).content | Out-File $env:temp\\ConfigureRemotingForAnsible.ps1",
            "powershell.exe -ExecutionPolicy ByPass -File $env:temp\\ConfigureRemotingForAnsible.ps1 -EnableCredSSP",
            "Set-Service RdAgent -StartupType Disabled",
            "Set-Service WindowsAzureTelemetryService -StartupType Disabled",
            "Set-Service WindowsAzureGuestAgent -StartupType Disabled",
            "Remove-ItemProperty -Path 'HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Setup\\SysPrepExternal\\Generalize' -Name '*'"
          ]
      },
      {
        "type": "windows-restart",
        "restart_check_command": "powershell -command \"& {Write-Output 'restarted.'}\""
      },
      {
        "type": "powershell",
        "inline": [
          "& $env:SystemRoot\\System32\\Sysprep\\Sysprep.exe /oobe /generalize /quiet /quit",
          "while($true) { $imageState = Get-ItemProperty HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Setup\\State | Select ImageState; if($imageState.ImageState -ne 'IMAGE_STATE_GENERALIZE_RESEAL_TO_OOBE') { Write-Output $imageState.ImageState; Start-Sleep -s 10  } else { break } }"
        ]
      }
    ]

This should now fix the issue and allow deployment to continue!