Running packer hcl2_upgrade and getting pkr.hcl file with template hcl2_upgrade unexpected in operand

Introduction

Since Packer v1.7.0, it is recommended to use HCL2 instead of JSON for Packer templates. The .pkr.hcl file generated by the hcl2_upgrade command, which converts a Packer template written in JSON to HCL2 format, will output "template: hcl2_upgrade:3: unexpected \"\\\\\" in operand" in the .pkr.hcl file generated by executing the .pkr.hcl command.

Solution

github.com

In this case, the \" (escaped quote) used for escaping was not parsing JSON properly. You can work around this problem by changing \" (escaped quote) to backtick.

Before

Running packer hcl2_upgrade on a JSON file defined as follows...

{
  "builders": [{
    "type": "amazon-ebs", ...
    ...
    "ami_name": "ami_name-{{isotime \"2006-01-02-15-04-MST\"| clean_resource_name}}"
  }], }
}

The following .pkr.hcl file will be generated.

# could not parse template for the following block: "template: hcl2_upgrade:3: unexpected \"\\\\\" in operand"

source "amazon-ebs" "autogenerated_1" {
  ami_name = "ami_name-{{isotime \"2006-01-02-15-04-MST\"| clean_resource_name}}"

After

After changing the description and running packer hcl2_upgrade...

{
  "builders": [{
    "type": "amazon-ebs",.
    ...
    "ami_name": "ami_name-{{isotime `2006-01-02-15-04-MST`| clean_resource_name}}"
  }], ...
}

"template: hcl2_upgrade:3: unexpected \"\\\\\" in operand" is not output in the .pkr.hcl file, but a .pkr.hcl file using the intended format (legacy_isotime).

source "amazon-ebs" "autogenerated_1" {
  ami_name = "ami_name-{{ clean_resource_name `${legacy_isotime("2006-01-02-15-04-MST")}` }}"

References

github.com

developer.hashicorp.com

developer.hashicorp.com

developer.hashicorp.com

developer.hashicorp.com

www.packer.io