DEV Community

Yuta Mizui
Yuta Mizui

Posted on • Updated on

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

https://github.com/hashicorp/packer/issues/10728#issuecomment-793199077

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}}"
  }], }
}
Enter fullscreen mode Exit fullscreen mode

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}}"
Enter fullscreen mode Exit fullscreen mode

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}}"
  }], ...
}
Enter fullscreen mode Exit fullscreen mode

"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")}` }}"

Enter fullscreen mode Exit fullscreen mode

References

https://github.com/hashicorp/packer/issues/10728

https://developer.hashicorp.com/packer/docs/v1.7.x/commands/hcl2_upgrade

https://developer.hashicorp.com/packer/tutorials/configuration-language/hcl2-upgrade

https://developer.hashicorp.com/packer/docs/templates/hcl_templates/functions/datetime/legacy_isotime

https://developer.hashicorp.com/packer/docs/templates/legacy_json_templates/engine

https://www.packer.io/

Top comments (0)