使用Packer创建Linux镜像失败:无产物且脚本非零退出码报错
问题场景
在Windows PowerShell中使用Packer 1.8.3(windows_amd64)执行以下packer.json文件创建Azure Linux镜像,相关资源可正常创建和删除,但最终未生成目标镜像,报错如下:
Some builds didn't complete successfully and had errors:
--> azure-arm: Script exited with non-zero exit status: 1. Allowed exit codes are: [0]
==> Builds finished but no artifacts were created.
使用的packer.json内容:
{ "builders": [{ "type": "azure-arm", "client_id": "fb61f35d-99c5-43f8-9444-f4a3b96fd1f0", "client_secret": "DV-8Q~CJCeAfsc.WBm5eJ5ItVdcqnUebd3zhJb-o", "tenant_id": "67b304ff-0032-477b-b33f-c7a9de6ab0a5", "subscription_id": "315c9c99-62bc-42ff-bd23-d85a808a5609", "managed_image_name": "MyUbuntuImage", "managed_image_resource_group_name": "newgroup", "os_type": "Linux", "image_publisher": "Canonical", "image_offer": "UbuntuServer", "image_sku": "16.04-LTS", "location": "eastus", "vm_size": "standard_B1ms" }], "provisioners":[{ "execute_command": "chmod +x {{ .path }}; {{ .Vars }} sudo -E sh '{{ .path }}'", "inline": [ "apt-get update", "apt-get install nginx -y", "apt-get install stress -y", "systemct1 enable nginx", "/usr/sbin/waagent -force -deprovision+user && export HISTSIZE=0 && sync" ], "inline_shebang": "/bin/sh -x", "type": "shell" }] }
解决步骤
修正拼写错误
查看provisioners的inline命令,发现systemct1 enable nginx存在拼写错误,正确的命令应为systemctl enable nginx。这个错误会直接导致脚本执行失败,返回非0退出码,中断Packer的构建流程。启用详细日志排查剩余问题
若修正拼写后仍有问题,执行Packer时添加-debug参数,这样在脚本出错时会保持VM不销毁,你可以登录到VM中查看具体的命令执行日志,定位其他可能的错误:packer build -debug your-packer-file.json或者使用
-on-error=ask参数,让Packer在出错时询问是否保留VM:packer build -on-error=ask your-packer-file.json验证waagent命令兼容性
Ubuntu 16.04的waagent版本支持-deprovision+user参数,但可以在脚本开头添加set -e确保脚本在出错时立即终止,方便定位问题。另外,执行完waagent命令后,Packer会自动处理VM的关机和镜像创建,无需额外操作。
内容的提问来源于stack exchange,提问作者sruthi K

