Defaulting variables in Packer Template?

Hi Guys,

I’m running a packer build through a Gitlab CICD pipline.

Gitlab provides the environment variables during the run so no problems there.

However during the template coding phase I want to be able to run a local task (VSCode task) to validate the json I am writing without having to commit. Unfortunately all the variables which would normally be populated by Gitlab are coming up blank.

Is there a syntax to allow a default value to be substituted if needed like is possible in bash?

Something like…


Thanks in advance
Ian Carson

Hi @carsoni,

Welcome to our community! :wave:

Packer supports setting default values for User Variables. Those values can be overridden when building an image using either the -var or -var-file options.

Packer does support using Environment Variables in your User Variables. However, the value of a user variables will default to a blank string if the referenced environment variable is not set. As a workaround, you could first generate a JSON -var-file using values from your environment, and then provide that file to Packer during the build process.

Thanks for that @blake :grinning:
Looks like

    "checksum_type": "sha256"

as a var-file passed to my validate task has done the trick. It overwrites the variable in the packer template while leaving all the others to be used.

Nice one!