2

I am working on building a new ami with packer ONLY if a result (shell command) matches a value in the "provisioner" section

I am looking for a solution to have a conditional statement in "provisioner" section

"provisioners": [
  {
    "type": "shell",
    "inline": [
      res=f(20)
    ]

in this example, I want to define a condition if res = 10 then continue (so packer will generate aws ami) else stop the execution (and print a message)

Maurice Amar
  • 129
  • 1
  • 9

1 Answers1

1

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.
Carlo Mencarelli
  • 678
  • 5
  • 16