Return variables from shell provisioner into packer variables

This may be a stupid question. not sure if this is even possible

I know how to push variables into a shell provisioner process… but is it even possible to return variables so packer can use them for future … like tagging images


export NGINX_VERSION=$(nginx -v)

then in the tagging process (bad example here)

"tags": {
    "nginx_version": "{{env `NGINX_VERSION`}}",

Did you just try it out in the meantime?

strangely no, I read every piece of documentation I could find about the env process relating to exporting shell vars back into packer. couldn’t find any.

if this works … then well… lol awesome.

ill give it a go :wink:

1 Like

Did this work for you? I’ve recently become interested in this as well.

@freibuis sharing variables across provisioners is not possible without the use of some auxiliary file on the guest machine, as provisioner scripts are executed in isolation. So state such as variables from one script won’t carry on to the next.

A workaround here would be to persist the environment variables to a file on the guest machine, then do one of the following to load the environment variables into the next provisioner:

  1. Update the commands or scripts for the provisioner where you want to use the shared variable so that it sources the shared env var file before executing any additional commands.
  2. Use the execute_command option to source the shared env var file . For example "execute_command": "chmod +x {{.Path}}; . /tmp/shared_vars && {{.Path}}"

I hope this helps.

@nywilken … nifty!!!.
so write them out to the shared file. then “grab” them out of that. :thinking: not sure why I didnt think of that to be frank

that would need to be tested tho…

question. will the “execute_command” pass the variables after the packer build process? or would the file need to be there first? as in chicken or the egg?

Apologies for the slow response here. The execute_command will pass the variable information after the build process, at provision time for each provisioner. So the shared file must exist prior to running the first provisioner that needs to read that file.

If in your build step, guessing via some init script or user data script, the file is created the provisioner with the custom execute_command would run after the build and load the shared file at the time of execution; a custom execute_command will need to be set for each proivisioner that would require access to the shared env file.

If you plan on using a provisioner to create or update the file then any changes to the shared var file would only be available to subsequent provisioners using the custom execute_command.