Intermittent apt-get install issues when creating an AMI using Packer

Most likely, you ran into a race condition with cloud-init. This packer issue gives some insights, and I have tried the following suggestion given by the OP with success:

echo "waiting 180 seconds for cloud-init to update /etc/apt/sources.list"
timeout 180 /bin/bash -c \
  'until stat /var/lib/cloud/instance/boot-finished 2>/dev/null; do echo waiting ...; sleep 1; done'

In my case prepending the text /usr/bin/cloud-init status --wait && to the execute_command guy solved the issue,

json file:

"provisioners" : [
    {
        "type" : "shell",
        "script" : "./setup.sh",
        "execute_command" : "/usr/bin/cloud-init status --wait && \
            sudo -E -S sh '{{ .Path }}'"
    }
]