powershelldevopspackerhashicorp

packer cant pass -var-file as input to build


I am struggling with packer to pass -var-file as input to build. It's some kind of bug or I'm doing something wrong ? Please help :)

I have simple clean-null-build.pkr.hcl build:

source "null" "first" {
    communicator = "none"
}

build {
    name = "my first build"
    source "null.first" {
    }

provisioner "shell-local" {
    inline = ["echo ${var.foo}"]

}
}

And I have splited variable file from main build file variables.pkrvars.hcl :

variable "foo" {
    default = "test"
}

And i got error like this:

enter image description here

Then i tried change variable file content like this:

foo="test"

Then I got error like this:

enter image description here

And finally I tried to use json format like this also I renamed file name like variables.pkrvars.json :

{
    "foo" : "test"
}

Also got similar error :

enter image description here

packer version Packer v1.8.3 maybe someone had similar problem ? If I create variable block inside main build its works like expected..


Solution

  • Your first attempt failed because you passed a Packer config file as a variable input file argument. Your second attempt failed because you removed the Packer config file declaring the variable after correcting the input file. Your third attempt failed for the same reason as the second. All three attempts also failed because you targeted a specific template instead of a template and config directory (since you have multiple).

    You need to correct the input file (as in the second attempt) while not removing the config file declaring the variable (as in the first attempt):

    # variables.pkr.hcl
    variable "foo" {
      type    = string
      default = "test"
    }
    
    # foo.pkrvars.hcl
    foo = "test"
    

    and then pass the input variable as an argument with the corrected target:

    packer build -var-file="foo.pkrvars.hcl" .
    

    Note this is consistent with the error messages thrown by Packer and their suggested resolution.