Packer templates: Add more verbosity to shell provisioners

2 min read | by Jordi Prats

If we use shell scripts as provisioners with packer errors can be confusing:

==> 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: Error removing temporary script at /tmp/script_9722.sh! ==> Some builds didn't complete successfully and had errors: --> amazon-ebs: Error removing temporary script at /tmp/script_9722.sh! ==> Builds finished but no artifacts were created. 

We can tell there is an error, but it's hard to tell what's going on

If it is executed as script as follows:

(...)  "provisioners": [  {  "type": "shell",  "script": "/opt/provisioners/example_script.sh"  }], (...) 

We can change it to inline adding the -x flag to enable further verbosity:

(...)  "provisioners": [  {  "type": "shell",  "inline": ["/bin/bash -x /opt/provisioners/example_script.sh"]  }], (...) 

So we can get a more detailed error:

==> amazon-ebs: Provisioning with shell script: /tmp/packer-shell069763962  amazon-ebs: /bin/bash: /opt/provisioners/example_script.sh: No such file or directory ==> 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: Script exited with non-zero exit status: 127.Allowed exit codes are: [0] ==> Some builds didn't complete successfully and had errors: --> amazon-ebs: Script exited with non-zero exit status: 127.Allowed exit codes are: [0] ==> Builds finished but no artifacts were created. 

By adding executing the script explicitly with bash with the -x flag we will make sure it will print commands and their arguments as they are executed. For example, if we run the following shell script with the -x flag:

#!/bin/bash echo first example echo third $(echo second) 

We will be able to see the actual execution like follows:

$ bash -x test.sh  + echo first example first example ++ echo second + echo third second third second 

Posted on 26/01/2022

Categories