Problems using Packer and Ansible with WinRM Connection

First of all I apologise for the length of this post, but I thought it best to be thorough and detail what I’ve tried so far.
I’m also still somewhat new to Ansible so forgive me if I’m doing something stupidly obviously wrong.

So I’m attempting to create a packer build and use Ansible to do my configuration/application installation work, but I’m having some troubles when attempting to use the Ansible WinRM connector, and Googling has given me no real answers, so I’m hoping someone here might be able to help or point me in the right direction.

Prior to making my ansible call I have uploaded and run the ConfigureRemotingForAnsible.ps1 script which completes successfully. On accessing the in-progress VM build I can see that it has created a cert and configured WinRM, with WinRM listening on Ports 5985 and 5986. The built-in Windows Firewall is completely disabled at this stage.

My initial packer Ansible call was,

{
    "type": "ansible",
    "playbook_file" : "./playbooks/{{user `playbook`}}.yml",
    "extra_arguments": [
        "--connection", "packer", "-vvv",
        "--extra-vars", "ansible_connection=winrm ansible_winrm_server_cert_validation=ignore"
    ]
},

However this fails in the Gathering Facts section with the error,

vsphere-iso: fatal: [default]: UNREACHABLE! => {
vsphere-iso:     "changed": false,
vsphere-iso:     "msg": "ssl: auth method ssl requires a password",
vsphere-iso:     "unreachable": true
vsphere-iso: }

My next step was to implement an ansible_username and ansible_password,

{
    "type": "ansible",
    "playbook_file" : "./playbooks/{{user `playbook`}}.yml",
    "extra_arguments": [
        "--connection", "packer", "-vvv",
        "--extra-vars", "ansible_connection=winrm ansible_winrm_server_cert_validation=ignore ansible_user=packer ansible_password=password"
    ]
},

The username ‘packer’ is the one specified in packer itself and I’ve verified that it exists as a local user and is in the local administrators group. The password set is the same one as the one set in packer itself. Unfortunately this fails with a new error,

vsphere-iso: <127.0.0.1> ESTABLISH WINRM CONNECTION FOR USER: packer on PORT 36344 TO 127.0.0.1
==> vsphere-iso: failed to handshake
vsphere-iso: fatal: [default]: UNREACHABLE! => {
vsphere-iso:     "changed": false,
vsphere-iso:     "msg": "ssl: [SSL: UNKNOWN_PROTOCOL] unknown protocol (_ssl.c:618)",
vsphere-iso:     "unreachable": true
vsphere-iso: }

This port is incorrect so I added an ansible_port=5985 to my ansible call,

{
    "type": "ansible",
    "playbook_file" : "./playbooks/{{user `playbook`}}.yml",
    "extra_arguments": [
        "--connection", "packer", "-vvv",
        "--extra-vars", "ansible_connection=winrm ansible_winrm_server_cert_validation=ignore ansible_user=packer ansible_password=password ansible_port=5985"
    ]
},

However this then fails with the error,

vsphere-iso: <127.0.0.1> ESTABLISH WINRM CONNECTION FOR USER: packer on PORT 5985 TO 127.0.0.1
vsphere-iso: fatal: [default]: UNREACHABLE! => {
vsphere-iso:     "changed": false,
vsphere-iso:     "msg": "plaintext: ('Connection aborted.', error(111, 'Connection refused'))",
vsphere-iso:     "unreachable": true
vsphere-iso: }

So I cannot figure out why the connection is being refused. The username and password are correct, the user is a local account and a member of the local administrators group, Windows Firewall is disabled, WinRM appears to be listening. So I’m at a loss as to what else I can check and what else might be wrong.

For reference the playbook I’m running is just this,

---
- hosts: all
  become: false

  roles:
    - myrole1

As all of the failures are in the Gathering Facts section however I don’t think the content of my roles is causing an issue.

I should also point out that if I make this ansible call,

{
    "type": "ansible",
    "playbook_file" : "./playbooks/{{user `playbook`}}.yml",
    "extra_arguments": [
        "--connection", "packer", "-vvv",
        "--extra-vars", "ansible_shell_type=powershell ansible_shell_executable=None"
    ]
},

Then the connection goes via SSH and works absolutely fine, but only while I’m using Ansible 2.7. The moment I update to Ansible 2.9 it fails with this error,

vsphere-iso: <127.0.0.1> (1, '', "Warning: Permanently added '[127.0.0.1]:34657' (RSA) to the list of known hosts.\r\nParameter format not correct - ;\r\n")
    vsphere-iso: <127.0.0.1> Failed to connect to the host via ssh: Warning: Permanently added '[127.0.0.1]:34657' (RSA) to the list of known hosts.
    vsphere-iso: Parameter format not correct - ;
    vsphere-iso: fatal: [default]: FAILED! => {
    vsphere-iso:     "ansible_facts": {},
    vsphere-iso:     "changed": false,
    vsphere-iso:     "failed_modules": {
    vsphere-iso:         "setup": {
    vsphere-iso:             "failed": true,
    vsphere-iso:             "module_stderr": "Warning: Permanently added '[127.0.0.1]:34657' (RSA) to the list of known hosts.\r\nParameter format not correct - ;\r\n",
    vsphere-iso:             "module_stdout": "",
    vsphere-iso:             "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error",
    vsphere-iso:             "rc": 1
    vsphere-iso:         }
    vsphere-iso:     },
    vsphere-iso:     "msg": "The following modules failed to execute: setup\n"
    vsphere-iso: }

But as soon as I revert back to Ansible 2.7, it works fine again.

1 Like

@dpower1985, I’m having very similar problems and can’t find anything on Google to help! Did you manage to resolve the issue? Did you just end up rolling back to a previous version?

What the hell, doesn’t anyone from HashiCorp monitor this discussion forum? Why not? This seems like something that is going to be used by a large number of companies if it worked. I having the same issue. If I use a PowerShell script, it connects via winrm just fine, and runs the script.
ansible-playbook 2.9.13

==> amazon-ebs: Connected to WinRM!
==> amazon-ebs: Provisioning with Ansible...
==> amazon-ebs: Executing Ansible: ansible-playbook --extra-vars packer_build_name=amazon-ebs packer_builder_type=amazon-ebs -o IdentitiesOnly=yes -i /tmp/packer-provisioner-ansible560817650 /codebuild/output/src481803175/src/git.nylcloud.com/Cloud-Team/packer-aws-mee-win2016/ansible/playbook.yml -e ansible_ssh_private_key_file=/tmp/ansible-key385897759 --connection packer -vvv --extra-vars ansible_shell_type=powershell ansible_shell_executable=None
amazon-ebs: ansible-playbook 2.9.13
amazon-ebs:   config file = None
amazon-ebs:   configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
amazon-ebs:   ansible python module location = /root/.pyenv/versions/3.8.3/lib/python3.8/site-packages/ansible
amazon-ebs:   executable location = /root/.pyenv/versions/3.8.3/bin/ansible-playbook
amazon-ebs:   python version = 3.8.3 (default, Aug 28 2020, 18:43:52) [GCC 7.3.1 20180712 (Red Hat 7.3.1-9)]
amazon-ebs: No config file found; using defaults
amazon-ebs: host_list declined parsing /tmp/packer-provisioner-ansible560817650 as it did not pass its verify_file() method
amazon-ebs: script declined parsing /tmp/packer-provisioner-ansible560817650 as it did not pass its verify_file() method
amazon-ebs: auto declined parsing /tmp/packer-provisioner-ansible560817650 as it did not pass its verify_file() method
amazon-ebs: Parsed /tmp/packer-provisioner-ansible560817650 inventory source with ini plugin
amazon-ebs:
amazon-ebs: PLAYBOOK: playbook.yml *********************************************************
amazon-ebs: 1 plays in /codebuild/output/src481803175/src/git.nylcloud.com/Cloud-Team/packer-aws-mee-win2016/ansible/playbook.yml
amazon-ebs:
amazon-ebs: PLAY [all] *********************************************************************
amazon-ebs:
amazon-ebs: TASK [Gathering Facts] *********************************************************
amazon-ebs: task path: /codebuild/output/src481803175/src/git.nylcloud.com/Cloud-Team/packer-aws-nyl-win2016/ansible/playbook.yml:2
amazon-ebs: fatal: [default]: FAILED! => {
amazon-ebs:     "msg": "the connection plugin 'packer' was not found"
amazon-ebs: }
amazon-ebs:
amazon-ebs: PLAY RECAP *********************************************************************
amazon-ebs: default                    : ok=0    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0
amazon-ebs:
==> amazon-ebs: Terminating the source AWS instance...

I too have tried dozens of variations extravars and configurations. Here is the last.

“type”: “ansible”,
“playbook_file”: “ansible/playbook.yml”,
“user”: “Administrator”,
“extra_arguments”: [
“-c”, “Administrator”,
“-vv”,
“-e”, “ansible_user=Administrator ansible_winrm_server_cert_validation=ignore ansible_shell_type=powershell ansible_shell_executable=None ansible_python_interpreter=auto_silent”
]

I feel like this is close.

I will be amazed if no one replies, my experience with the Terraform side has been very helpful.

Hi all,

A brief guide to using winRM with Packer can be found here: https://www.packer.io/docs/provisioners/ansible.html#winrm-communicator

The “use_proxy” option mentioned in that guide was introduced this past May, in version 1.5.6. I strongly recommend upgrading to at least that version in order to use Ansible with WinRM.

Give the use_proxy: false option a try and let me if that solves your issues.

Thanks much for the responce. I applied the settings and upgraded to the latest version of Packer. This is what I have so far.

Build ‘amazon-ebs’ errored after 2 seconds 541 milliseconds: Couldn’t find specified instance profile: AccessDenied: User: arn:aws:sts::169831244:assumed-role/mee-alpha-tech-ami-pipeline-role/AWSCodeBuild-0142b2f0-6abe-4539-a678-e851b83de8af is not authorized to perform: iam:GetInstanceProfile on resource: instance profilenyl-alpha-tech-packer-instance-profile
status code: 403, request id: dc8ddddff55-ef1e-4c7f-94040d-eb52b5973333
==> Wait completed after 2 seconds 541 milliseconds
==> Some builds didn’t complete successfully and had errors:
–> amazon-ebs: Couldn’t find specified instance profile: AccessDenied: User: arn:aws:sts::169830333344:assumed-role/mee-alpha-tech-ami-pipeline-role/AWSCodeBuild-014666f0-6abe-4666-a678-e851b66le8af is not authorized to perform: iam:GetInstanceProfile on resource: instance profilenyl-alpha-tech-packer-instance-profile
status code: 403, request id: dc89a182-ef1e-4c7f-9fed-eb52b5974414

Not sure what 1.6.2 does so differently, but this error has us stopped, so I rolled back to that 1.4.2 version.
is not authorized to perform: iam:GetInstanceProfile on resource: instance profilemee-betaa-tech-packer-instance-profile.
Not sure what GetInstacnePorfile does different than the 1.4.2 version.

Would it be better if I put OppenSSH on my Windows servers and tried to use packer ansible connecting that way.

I was just able to reproduce your “plugin” issue with 1.6.2. I’ll look into it.

Oh nevermind, the plugin thing is from not setting no_proxy.

Okay, looks like you’re having issues even launching the instance because a new feature requires a new set of permissions that your user doesn’t have. I think validation was added in https://github.com/hashicorp/packer/pull/8247, which added a new permission requirement that we didn’t catch. Try setting SkipProfileValidation (added here: https://github.com/hashicorp/packer/issues/8452) to your config to bypass that check.

Looks like we have a connection, but something is wrong with the transport.

==> amazon-ebs: Provisioning with Ansible…
amazon-ebs: Not using Proxy adapter for Ansible run:
amazon-ebs: Using WinRM Password from Packer communicator…
==> amazon-ebs: Executing Ansible: ansible-playbook -e packer_build_name=“amazon-ebs” -e packer_builder_type=amazon-ebs -e ansible_winrm_server_cert_validation=ignore ansible_winrm_password=***** ansible_connection=winrm ansible_winrm_transport=basic -e ansible_password=***** -i /tmp/packer-provisioner-ansible992875251 /codebuild/output/src078149741/src/git.nylcloud.com/Cloud-Team/packer-aws-nyl-win2016/playbook.yml
amazon-ebs:
amazon-ebs: PLAY [all] *********************************************************************
amazon-ebs:
amazon-ebs: TASK [Gathering Facts] *********************************************************
amazon-ebs: [WARNING]: - attempting to recover: WinRMError
amazon-ebs: The pipe is being closed. (extended fault data: {‘transport_message’: ‘Bad
amazon-ebs: HTTP response returned from server. Code 500’, ‘http_status_code’: 500,
amazon-ebs: ‘wsmanfault_code’: ‘232’, ‘fault_code’: ‘s:Receiver’, ‘fault_subcode’:
amazon-ebs: ‘w:InternalError’})
amazon-ebs: fatal: [default]: FAILED! => {“msg”: “winrm send_input failed; \nstdout: \nstderr C\u0000a\u0000n\u0000n\u0000o\u0000t\u0000 \u0000s\u0000t\u0000a\u0000r\u0000t\u0000 \u0000W\u0000i\u0000n\u0000d\u0000o\u0000w\u0000s\u0000 \u0000P\u0000o\u0000w\u0000e\u0000r\u0000S\u0000h\u0000e\u0000l\u0000l\u0000 \u0000v\u0000e\u0000r\u0000s\u0000i\u0000o\u0000n\u0000 \u00006\u0000.\u00002\u0000.\u00006\u0000 \u0000b\u0000e\u0000c\u0000a\u0000u\u0000s\u0000e\u0000 \u0000i\u0000t\u0000 \u0000i\u0000s\u0000 \u0000n\u0000o\u0000t\u0000 \u0000i\u0000n\u0000s\u0000t\u0000a\u0000l\u0000l\u0000e\u0000d\u0000.\u0000\r\u0000\n\u0000”}
amazon-ebs:
amazon-ebs: PLAY RECAP *********************************************************************
amazon-ebs: default : ok=0 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0
amazon-ebs:
==> amazon-ebs: Provisioning step had errors: Running the cleanup provisioner, if present…
==> amazon-ebs: Terminating the source AWS instance…
==> amazon-ebs: Cleaning up any extra volumes…
==> amazon-ebs: No volumes to clean up, skipping
==> amazon-ebs: Deleting temporary security group…
==> amazon-ebs: Deleting temporary keypair…
Build ‘amazon-ebs’ errored after 3 minutes 14 seconds: Error executing Ansible: Non-zero exit status: exit status 2

==> Wait completed after 3 minutes 14 seconds

What do the relevant parts of your template (communicator info, ansible configuration) and user_data_file look like at this point?

1 Like

user_data.txt

net user Administrator SuperS3cr3t! wmic useraccount where "name='Administrator'" set PasswordExpires=FALSE

USERDATA SCRIPT FOR AMAZON SOURCE WINDOWS SERVER AMIS

BOOTSTRAPS WINRM VIA SSL

Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope LocalMachine -Force -ErrorAction Ignore
$ErrorActionPreference = “stop”

Remove any existing Windows Management listeners

Remove-Item -Path WSMan:\Localhost\listener\listener* -Recurse

Create self-signed cert for encrypted WinRM on port 5986

$Cert = New-SelfSignedCertificate -CertstoreLocation Cert:\LocalMachine\My -DnsName “packer-ami-builder”
New-Item -Path WSMan:\LocalHost\Listener -Transport HTTPS -Address * -CertificateThumbPrint $Cert.Thumbprint -Force

Configure WinRM

cmd.exe /c winrm quickconfig -q
cmd.exe /c winrm set “winrm/config” ‘@{MaxTimeoutms=“1800000”}’
cmd.exe /c winrm set “winrm/config/winrs” ‘@{MaxMemoryPerShellMB=“1024”}’
cmd.exe /c winrm set “winrm/config/service” ‘@{AllowUnencrypted=“true”}’
cmd.exe /c winrm set “winrm/config/client” ‘@{AllowUnencrypted=“true”}’
cmd.exe /c winrm set “winrm/config/service/auth” ‘@{Basic=“true”}’
cmd.exe /c winrm set “winrm/config/client/auth” ‘@{Basic=“true”}’
cmd.exe /c winrm set “winrm/config/service/auth” ‘@{CredSSP=“true”}’
cmd.exe /c winrm set “winrm/config/client/auth” ‘@{CredSSP=“true”}’
cmd.exe /c winrm set “winrm/config/service/auth” ‘@{Negotiate=“true”}’
cmd.exe /c winrm set “winrm/config/client/auth” ‘@{Negotiate=“true”}’
cmd.exe /c winrm set “winrm/config/service/auth” ‘@{Certificate=“true”}’
cmd.exe /c winrm set “winrm/config/client/auth” ‘@{Certificate=“true”}’
cmd.exe /c winrm set “winrm/config/listener?Address=*+Transport=HTTPS” “@{Port="5986”;Hostname="$env:ComputerName";CertificateThumbprint="$($Cert.Thumbprint)"}"
cmd.exe /c netsh advfirewall firewall add rule name=“WinRM-SSL (5986)” dir=in action=allow protocol=TCP localport=5986
cmd.exe /c net stop winrm
cmd.exe /c sc config winrm start=auto
cmd.exe /c net start winrm

win2019.json

{
“variables”: {
“region”: “{{env region}}”,
“environment”: “{{env env}}”,
“lob”: “{{env lob}}”,
“vpc_id”: “{{env vpc_id}}”,
“subnet_id”: “{{env subnet_id}}”,
“account”: “{{env account}}”,
“role”: “{{env iam_instance_profile}}”,
“kms_key”: “{{env kms_key_id}}”
},
“builders”: [
{
“type”: “amazon-ebs”,
“region”: “{{user region}}”,
“vpc_id”: “{{user vpc_id}}”,
“subnet_id”: “{{user subnet_id}}”,
“instance_type”: “t2.medium”,
“source_ami_filter”: {
“filters”: {
“virtualization-type”: “hvm”,
“name”: “Windows_Server-2019-English-Full-Base-*”,
“root-device-type”: “ebs”
},
“most_recent”: true,
“owners”: “amazon”
},
“ami_name”: “{{user lob}}-{{user environment}}-win2019”,
“user_data_file”: “scripts/user_data.txt”,
“communicator”: “winrm”,
“force_deregister”: true,
“winrm_insecure”: true,
“winrm_username”: “Administrator”,
“winrm_password”: “SuperS3cr3t!”,
“winrm_use_ssl”: true,
“winrm_port”: 5986,
“winrm_timeout”: “15m”,

  "iam_instance_profile": "{{user `role`}}",

  "skip_profile_validation" : true
}

],
“provisioners”: [
{
“type”: “powershell”,
“script”: “scripts/dansps.ps1”
},
{
“type”: “ansible”,

  "playbook_file": "playbook.yml",
  "user": "Administrator",
  "use_proxy": false,
  "extra_arguments": ["-vvv", "-e", "ansible_winrm_server_cert_validation=ignore ansible_password=SuperS3cr3t! ansible_connection=winrm ansible_winrm_transport=basic ansible_port=5986 ansible_shell_type=powershell ansible_python_interpreter=/usr/bin/python3"]

}

]

}
playbook.yml


  • hosts: all
    tasks:
    • name: Create directory structure
      ansible.windows.win_file:
      path: C:\Temp\folder\subfolder
      state: directory

ansible.cfg
empty.

I think this is better?

amazon-ebs: <10.184.21.6> ESTABLISH WINRM CONNECTION FOR USER: Administrator on PORT 5986 TO 10.184.21.6
amazon-ebs: EXEC (via pipeline wrapper)
amazon-ebs: fatal: [default]: UNREACHABLE! => {
amazon-ebs: “changed”: false,
amazon-ebs: “msg”: "Failed to create temporary directory.In some cases, you may have been able to authenticate and did not have permissions on the target directory. Consider changing the remote tmp path in ansible.cfg to a path rooted in “/tmp”, for more error information use -vvv. Failed command was: PowerShell -Version 6.2.6 -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -EncodedCommand

One of the Ansible engineers is suggesting the Packer may be doing something with an environmental variables ‘POWERSHELL_VERSION’ that may be causing this issue. 14:30 <@jborean93> i255d: https://github.com/ansible/ansible/blob/8f02819db02459ed144e131db3808dee0a7356db/lib/ansible/plugins… you have POWERSHELL_VERSION set in an env var which is causing the trouble

added now: I have a $PSversiontable in the powershell provisioner that shows it is version 5.1, when I switch the OS from 2019 to 2016, and the when the Ansible part runs is says this: amazon-ebs: <10.184.21.18> WINRM EXEC ‘PowerShell’ [’-Version’, ‘6.2.6’, ‘-NoProfile’, ‘-NonInteractive’, ‘-ExecutionPolicy’, ‘Unrestricted’, ‘-EncodedCommand’,
I am pretty sure the version 6.2.6 is the issue.

Interesting – I just looked in the Ansible provisioner code to see if I could figure out what’s going on.

Looks like Packer loads its current environment into the environment for the command to call Ansible. That’s not a practice Packer normally follows in other provisioners. That’s a bug I need to handle, but it was introduced a long time ago here and is a “feature” for some so it’ll take some time and thought before I deprecate it.

In the meantime, you may be able to work around this by unsetting POWERSHELL_VERSION from your environment before calling Packer, or by setting it to the correct version.

I wonder if I can install Powershell core on the servers before I try and do this, and if that would help.
Does packer suport PWSH for Powershell Core?

Also on my build speck I am going to try
export POWERSHELL_VERSION=None to my build spec file, or
aws configure set POWERSHELL_VERSION None
if that doesn’t work.

I have a $PSversiontable in the powershell provisioner that shows it is PowerShell version 5.1, when I switch the OS from 2019 to 2016, and the when the Ansible part runs is says this: amazon-ebs: <10.184.21.18> WINRM EXEC ‘PowerShell’ [’-Version’, ‘6.2.6’, ‘-NoProfile’, ‘-NonInteractive’, ‘-ExecutionPolicy’, ‘Unrestricted’, ‘-EncodedCommand’,
I am pretty sure the version 6.2.6 is the issue.

Here is someone who worked around this issue on reddit:

https://www.reddit.com/r/devops/comments/bdr9l3/packer_ansible_and_the_dreaded_winrm_in_aws/

captnron76
1 year ago
Hiyas…
for posterity in case anyone else comes across this thread:
The problem seems to be that CodeBuild sets an environment variable POWERSHELL_VERSION (amongst several other *_VERSION variables), in my case it was 6.1.3.
Ansible’s powershell.py unfortunately uses the same environment variable to enable PowerShell executed over WinRM with a specific version of PowerShell.
The fix for me at least was to unset POWERSHELL_VERSION before invoking packer, although doing that as a CodeBuild step didn’t seem to work (I didn’t spend long on it). Our call to packer is wrapped in a shell script anyway, so I did it there with success.
HTH,

I think the powershell.py above is this script below.
https://github.com/ansible/ansible/blob/8f02819db02459ed144e131db3808dee0a7356db/lib/ansible/plugins/shell/powershell.py#L35-L37,

Here is the part that shows where the POWERSHELL_VERSION is passed by code build to ansible.

_common_args = [‘PowerShell’, ‘-NoProfile’, ‘-NonInteractive’, ‘-ExecutionPolicy’, ‘Unrestricted’]

Primarily for testing, allow explicitly specifying PowerShell version via

an environment variable.

_powershell_version = os.environ.get(‘POWERSHELL_VERSION’, None)
if _powershell_version:
_common_args = [‘PowerShell’, ‘-Version’, _powershell_version] + _common_args[1:]

I don’t think Packer will work with Powershell core, but I’ve never tried it so I can’t say for certain.

So I am having this same exact issue when trying to build through a CodeBuild.

I have the following provisioner configured in Packer. Packer is able to connect with powershell and enumerate winrm. This is with Windows 2016.

    "provisioners": [
        {
            "type": "powershell",
            "environment_vars": [
                "WINRMPASS={{.WinRMPassword}}"
            ],
            "inline": [
                "Write-Host \"Automatically generated aws password is: $Env:WINRMPASS\"",
                "winrm enumerate winrm/config/Listener"
            ]
        },
        {
            "type": "ansible",
            "playbook_file": "ansible/playbook.yml",
            "user": "Administrator",
            "use_proxy": false,
            "ansible_env_vars": [ "WINRM_PASSWORD={{.WinRMPassword}}" ],
            "extra_arguments": [
                "-e", "ansible_winrm_transport=ntlm ansible_winrm_server_cert_validation=ignore",
                "-vvvv"
            ]
        },
        {
            "type": "powershell",
            "inline": [
                "C:/ProgramData/Amazon/EC2-Windows/Launch/Scripts/InitializeInstance.ps1 -Schedule",
                "C:/ProgramData/Amazon/EC2-Windows/Launch/Scripts/SysprepInstance.ps1 -NoShutdown"
            ]
        }
    ]

Here is my error from Packer.

    amazon-ebs: TASK [Gathering Facts] *********************************************************
    amazon-ebs: task path: /codebuild/output/src823294906/src/ansible/playbook.yml:2
    amazon-ebs: redirecting (type: modules) ansible.builtin.setup to ansible.windows.setup
    amazon-ebs: Using module file /root/.pyenv/versions/3.8.2/lib/python3.8/site-packages/ansible_collections/ansible/windows/plugins/modules/setup.ps1
    amazon-ebs: Pipelining is enabled.
    amazon-ebs: <172.30.167.125> ESTABLISH WINRM CONNECTION FOR USER: Administrator on PORT 5986 TO 172.30.167.125
    amazon-ebs: EXEC (via pipeline wrapper)
    amazon-ebs: [WARNING]: ERROR DURING WINRM SEND INPUT - attempting to recover: WinRMError
    amazon-ebs: The pipe is being closed.  (extended fault data: {'transport_message': 'Bad
    amazon-ebs: HTTP response returned from server. Code 500', 'http_status_code': 500,
    amazon-ebs: 'wsmanfault_code': '232', 'fault_code': 's:Receiver', 'fault_subcode':
    amazon-ebs: 'w:InternalError'})
    amazon-ebs: fatal: [default]: FAILED! => {
    amazon-ebs:     "msg": "winrm send_input failed; \nstdout: \nstderr \"\u0000\u001d \u001d \"\u0000 \u0000i\u0000s\u0000 \u0000n\u0000o\u0000t\u0000 \u0000a\u0000 \u0000v\u0000a\u0000l\u0000i\u0000d\u0000 \u0000W\u0000i\u0000n\u0000d\u0000o\u0000w\u0000s\u0000 \u0000P\u0000o\u0000w\u0000e\u0000r\u0000S\u0000h\u0000e\u0000l\u0000l\u0000 \u0000v\u0000e\u0000r\u0000s\u0000i\u0000o\u0000n\u0000.\u0000 \u0000 \u0000S\u0000p\u0000e\u0000c\u0000i\u0000f\u0000y\u0000 \u0000a\u0000 \u0000v\u0000a\u0000l\u0000i\u0000d\u0000 \u0000W\u0000i\u0000n\u0000d\u0000o\u0000w\u0000s\u0000 \u0000P\u0000o\u0000w\u0000e\u0000r\u0000S\u0000h\u0000e\u0000l\u0000l\u0000 \u0000v\u0000e\u0000r\u0000s\u0000i\u0000o\u0000n\u0000 \u0000o\u0000f\u0000 \u0000t\u0000h\u0000e\u0000 \u0000f\u0000o\u0000r\u0000m\u0000a\u0000t\u0000 \u0000m\u0000a\u0000j\u0000o\u0000r\u0000.\u0000m\u0000i\u0000n\u0000o\u0000r\u0000 \u0000v\u0000e\u0000r\u0000s\u0000i\u0000o\u0000n\u0000.\u0000\r\u0000\n\u0000"
    amazon-ebs: }
    amazon-ebs:
    amazon-ebs: PLAY RECAP *********************************************************************
    amazon-ebs: default                    : ok=0    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0

Ha I got it to work now with the -export POWERSHELL_VERSION=""in my buildspec. The problem was that I had copied it from i255d’s post on Powershell.org and the quotes were not standard quotes.