How to Pass Argument in Packer Provision Script?

I am struggling to pass input parameter to packer provisioning script. I have tried various options but no joy.

Objective is my provision.sh should accept input parameter which I send during packer build.

packer build -var role=abc test.json

I am able to get the user variable in json file however I am unable to pass it provision script. I have to make a decision based on the input parameter.

I tried something like

"provisioners": 
{
  "type": "shell",
  "scripts": [
  "provision.sh {{user `role`}}"
 ]
}

But packer validation itself is failed with no such file/directory error message.

It would be real help if someone can help me on this.

Thanks in advance.

2 Answers

You should use the environment_vars option, see the docs Shell Provisioner - environment_vars.

Example:

"provisioners": [
  {
    "type": "shell"
    "environment_vars": [
      "HOSTNAME={{user `vm_name`}}",
      "FOO=bar"
    ],
    "scripts": [
      "provision.sh"
    ],
  }
 ]
7

If your script is already configured to use arguments; you simply need to run it as inline rather than in the scripts array.

In order to do this, the script must exist on the system already - you can accomplish this by copying it to the system with the file provisioner.

  "provisioners": [
    {
      "type":        "file",
      "source":      "scripts/provision.sh",
      "destination": "/tmp/provision.sh"
    },
    {
      "type": "shell",
      "inline": [
        "chmod u+x /tmp/provision.sh",
        "/tmp/provision.sh {{user `vm_name`}}"]
    }
  ]
3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest