2019-12-18 09:51:32 -05:00
|
|
|
---
|
2019-12-18 09:59:16 -05:00
|
|
|
page_title: Generating code for config spec.
|
2020-04-02 19:39:47 -04:00
|
|
|
sidebar_title: Making a plugin HCL2 enabled
|
2020-03-18 18:46:47 -04:00
|
|
|
description: Learn how to generate the HCL2 configuration of your component easily.
|
2019-12-18 09:51:32 -05:00
|
|
|
---
|
|
|
|
|
|
|
|
# Auto Generate the HCL2 code of a plugin
|
|
|
|
|
2019-12-19 09:40:08 -05:00
|
|
|
From v1.5, Packer can be configured using HCL2. Because Packer has so many
|
2021-02-15 05:10:43 -05:00
|
|
|
builders, provisioners, and post-processors, we created a on code generation
|
|
|
|
tool to add the HCL2-enabling code more easily. You can use this code generator
|
|
|
|
to create the HCL2 spec code of your custom plugin simply. It's a Go binary
|
|
|
|
package and is located in
|
|
|
|
[`cmd/mapstructure-to-hcl2`](https://github.com/hashicorp/packer/tree/master/cmd/mapstructure-to-hcl2).
|
2019-12-18 09:51:32 -05:00
|
|
|
|
2019-12-19 09:40:08 -05:00
|
|
|
Say you want to configure the `Config` struct of a `Builder` in a package
|
|
|
|
located in `my/example-plugin/config.go`. Here are some simple steps you can
|
|
|
|
follow to make it HCL2 enabled:
|
2019-12-18 09:51:32 -05:00
|
|
|
|
2020-03-18 18:46:47 -04:00
|
|
|
- run `go install github.com/hashicorp/packer/cmd/mapstructure-to-hcl2`
|
2019-12-18 09:51:32 -05:00
|
|
|
|
2020-03-18 18:46:47 -04:00
|
|
|
- Add `//go:generate mapstructure-to-hcl2 -type Config` at the top of
|
|
|
|
`config.go`
|
2019-12-18 09:51:32 -05:00
|
|
|
|
2020-03-18 18:46:47 -04:00
|
|
|
- run `go generate ./my/example-plugin/...`
|
2019-12-18 09:51:32 -05:00
|
|
|
|
2020-03-18 18:46:47 -04:00
|
|
|
This will generate a `my/example-plugin/config.hcl2spec.go` file containing
|
|
|
|
the configuration fields of `Config`.
|
2019-12-18 09:51:32 -05:00
|
|
|
|
2020-03-18 18:46:47 -04:00
|
|
|
- Make sure that all the nested structs of `Config` are also auto generated the
|
2019-12-19 09:40:08 -05:00
|
|
|
same way.
|
2019-12-18 09:51:32 -05:00
|
|
|
|
2021-02-15 05:10:43 -05:00
|
|
|
- Now we only need to make your Builder implement the interface by adding the
|
2020-03-18 18:46:47 -04:00
|
|
|
following snippet:
|
2019-12-18 09:51:32 -05:00
|
|
|
|
2020-03-24 18:36:27 -04:00
|
|
|
```go
|
|
|
|
func (b *Builder) ConfigSpec() hcldec.ObjectSpec { return b.config.FlatMapstructure().HCL2Spec() }
|
|
|
|
```
|
2019-12-18 09:51:32 -05:00
|
|
|
|
2020-03-24 18:36:27 -04:00
|
|
|
From now on every time you add or change a field of Config you will need to
|
|
|
|
run the `go generate` command again.
|
2019-12-19 09:40:08 -05:00
|
|
|
|
2020-03-18 18:46:47 -04:00
|
|
|
A good example of this is the [Config struct of the amazon-ebs builder](https://github.com/hashicorp/packer/blob/master/builder/amazon/ebs/builder.go)
|