I'll start with a disclaimer: Building conditionally isn't something that a provisioner is really intended to do. Ideally that kind of logic should be handled outside of the packer build process perhaps in a build pipeline like @MattSchuchard suggested. Examples of build pipeline tools are: Jenkins, CircleCI, Drone.IO
However: If you really need to have this logic built into the provisioner, Packer terminates and exits on a non-zero error code so you could do something like this:
"provisioners": [
{
"type": "shell",
"inline": [
"if [ $res -eq f(20) ]; then echo $res && exit 0; else echo "Incorrect result" && exit 1; fi"
]
}
]
You can further tweak this by using the valid_exit_codes
option and defining which exit codes you are expecting from the specific circumstances you're looking to validate. Ref: https://www.packer.io/docs/provisioners/shell.html#valid_exit_codes
Example Output:
$ packer build -var-file=provisioner-test.json build.json
==> amazon-ebs: Prevalidating AMI Name: Test-37Cv9mXMGqw5zAV
amazon-ebs: Found Image ID: ami-09693313102a30b2c
==> amazon-ebs: Creating temporary keypair: packer_5d96a8b4-ef4d-a705-a393-076457bdc3ea
==> amazon-ebs: Launching a source AWS instance...
==> amazon-ebs: Adding tags to source instance
amazon-ebs: Adding tag: "Name": "Packer Builder"
amazon-ebs: Instance ID: i-0ca4d944fe99255da
==> amazon-ebs: Waiting for instance (i-0ca4d944fe99255da) to become ready...
==> amazon-ebs: Using ssh communicator to connect: 10.0.24.189
==> amazon-ebs: Waiting for SSH to become available...
==> amazon-ebs: Connected to SSH!
==> amazon-ebs: Provisioning with shell script: /var/folders/mg/wc582qjx0y759zw3hfwxwjmm0000gp/T/packer-shell814735146
amazon-ebs: Incorrect result
==> 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 keypair...
Build 'amazon-ebs' errored: Script exited with non-zero exit status: 1.Allowed exit codes are: [0]
==> Some builds didn't complete successfully and had errors:
--> amazon-ebs: Script exited with non-zero exit status: 1.Allowed exit codes are: [0]
==> Builds finished but no artifacts were created.