Packer conditionally using Vault

Just switched from JSON → HCL2 which gives more flexibility.

When building up new env’s from scratch I have a need to create a Windows image without pulling secrets from Vault since that endpoint does not exist (yet).

So want to avoid repeating myself by having multiple hcl build files with pretty much the same content.

Tried googling for “packer conditionals” but ended up short. I.e when declaring a few secret locals variables have it be from vault() or fallback to env(). The thing is env() only works in definitions and vault() only for locals.

Would have been nice to do:

myypass =vault("path","key", var.env_mypass)

I.e allow the vault function to take a default value or something similar…
And use the default in the definition to set that var from env using env() function
Anyone with a workaround for that scenario??

Also finding the auto-loading of hcl files to not work as documented.

The other option was to have a win2019-vault.pkr.hcl and a win2019-no-vault.pkr.hcl.
But pointing out the file instead of doing a “packer build .” means non of the other *.auto.pkr.hcl files gets loaded. Strange???

Also found this about fallback to ENVs … Does not work or vault vars…

Environment Variables

As a fallback for the other ways of defining variables, Packer searches the environment of its own process for environment variables named PKR_VAR_ followed by the name of a declared variable.

Ok … Found how to do this …


locals {
   mypass = "${ var.mypass != "" ? var.mypass : vault("path", "key")}"

Then use the local.mypass through out the build…

Then in

variable "mypass" {
   sensitive = true
   default = env("mypass")

The running via docker:

docker run .....
  --env-file envs \
  image build .

Which demands the file envs to contain at least:


Off course one should not have cleartext passwords in textfiles. But the ENV should be passed at buildtime…