2021-02-16 14:31:05 +01:00

78 lines
2.1 KiB
Plaintext

---
page_title: Use jq and Packer to comment your templates - Guides
sidebar_title: Use jq to strip comments from a Packer template
description: |-
You can add detailed comments beyond the root-level underscore-prefixed field
supported by Packer, and remove them using jq.
---
# How to use jq to strip unsupported comments from a Packer template
-> **Note:** Packer supports HCL2 from version 1.6.0, the Hashicorp Configuration
Language allows to comment directly in template files. Consider upgrading your
JSON template to HCL2 using the `packer hcl2_upgrade` command.
One of the biggest complaints we get about Packer is that JSON doesn't use comments.
For Packer JSON templates, you can add detailed comments beyond the root-level underscore-prefixed field supported by Packer, and remove them using jq.
Let's say we have a file named `commented_template.json`
```json
{
"_comment": ["this is", "a multi-line", "comment"],
"builders": [
{
"_comment": "this is a comment inside a builder",
"type": "null",
"communicator": "none"
}
],
"_comment": "this is a root level comment",
"provisioners": [
{
"_comment": "this is a different comment",
"type": "shell",
"_comment": "this is yet another comment",
"inline": ["echo hellooooo"]
}
]
}
```
```shell-session
$ jq 'walk(if type == "object" then del(._comment) else . end)' commented_template.json > uncommented_template.json
```
will produce a new file containing:
```json
{
"builders": [
{
"type": "null",
"communicator": "none"
}
],
"provisioners": [
{
"type": "shell",
"inline": ["echo hellooooo"]
}
]
}
```
Once you've got your uncommented file, you can call `packer build` on it like
you normally would.
## The walk function
If your install of jq does not have the walk function and you get an error like
```text
jq: error: walk/1 is not defined at <top-level>,
```
You can create a file `~/.jq` and add the [walk function](https://github.com/stedolan/jq/blob/ad9fc9f559e78a764aac20f669f23cdd020cd943/src/builtin.jq#L255-L262) to it by hand.