Packer variable interpolation

I have two var files one

  variable: value


  variable: "{{env `VALUE`}}"

If I run

packer build -var-file 1.json -var-file 2.json ebs.json


packer build -var-file 2.json -var-file 1.json ebs.json

What will be precedence? Is there a way to run -var 'variable=$VALUE'? If so what will take precedeance -var-file or -var?

Hi, thanks for reaching out. Full docs can be found here: User Variables - Templates | Packer by HashiCorp but the tl;dr is that the later-specified variables, whether from -var or -var-file, override earlier-specified ones.

-var "variable=$VALUE" should work; you’re probably getting messed up because your example uses single quotes which in the shell mean you want a string literal instead of expanding the given variable.

Thank you. If the same value exists in var-file and passed as variable (“var=$VALUE”), which one will takes precedence? I couldn’t find the precedence/interpolation from the docs.

It looks like the precedence is only documented for versions > 1.5:

I would be surprised of the precedence rules changed from 1.4 to 1.5, but we should defer to the maintainer.

That’s useful. Thanks for the document.

The document brucellino is specific to HCL templates, not JSON templates.

The doc I linked is for JSON templates, but it appears to be out of date. Based on some basic local tests, it looks like values set on the cli override values sent in a var-file or the template itself. Values in a var-file override values set in the template. So the order goes cli > var-file > template.

You can validate this for yourself using a null builder test:


	"variables": {
		"thing": "template"
	"builders": [
			"type": "null",
			"communicator": "none"
	"provisioners": [
			"type": "shell-local",
			"inline": ["echo {{ user `thing`}}"]


	"thing": "varfile"

run using:

packer build -var "thing=cli" -var-file=var_file.json test_var_precedence.json

then swap the order of the arguments, or omit some arguments from the command.

All this said, I’d recommend using the hcl2_upgrade command to move to using HCL and then refer to the document that brucellino linked. The experience of writing templates in HCL is much nicer than that of writing templates in JSON, and moving forward from v 1.7 some new core features will only be added for HCL, as it will be out of beta and JSON templates will enter a legacy support phase before being deprecated.

1 Like