Search code examples
packerhcl

How to set Packer variables in HCL2


I am new to packer and need help to understand the variables usage

so I have a main build.pck.hcl file with source and other sections where I want to use variables defined in another file like this:

...
client_id = var.client_id
...

I created another file for variables only:

account.pkr.hcl

variable "client_id" {
    type = string
}

the I start packer like this:

packer build -color=false -debug  -var "client_id=123" -var-file account.pkr.hcl build.pck.hcl

but I always get an error while running:

Error: Variable declaration in a .pkrvar file

  on account.pkr.hcl line 14, in variable "client_id":
  14: variable "client_id" {

A .pkrvar file is used to assign values to variables that have already been
declared in .pkr files, not to declare new variables. To declare variable
"client_id", place this block in one of your .pkr files, such as
variables.pkr.hcl

To set a value for this variable in account.pkr.hcl, use the definition syntax
instead:
    client_id = <value>

What I am missing ? How to fix that ?

I want to some variables have default value and some of them will be passed on command line

P.S. If I changed packer build command and pass a folder path where files are I get an error:

Error: Undefined -var variable

A "client_id" variable was passed in the command line but was not found in known
variables. To declare variable "client_id", place this block in one of your .pkr
files, such as variables.pkr.hcl


Solution

  • It looks like you are using -var-file because you think you need to tell packer where to find that file. In reality, you don't need to do that and you simply need to use . as a context when running packer build, as packer will load all files ending in .pkr.hcl.

    The following should work for you:

    $ packer build -color=false -debug -var "client_id=123" .