github.com/hashicorp/packer@v1.14.3/website/content/guides/hcl/component-object-spec.mdx (about)

     1  ---
     2  page_title: Generating code for config spec.
     3  description: Learn how to generate the HCL2 configuration of your component easily.
     4  ---
     5  
     6  # Auto Generate the HCL2 code of a plugin
     7  
     8  From v1.5, Packer can be configured using HCL2. Because Packer has so many
     9  builders, provisioners, and post-processors, we created a on code generation
    10  tool to add the HCL2-enabling code more easily. You can use this code generator
    11  to create the HCL2 spec code of your custom plugin simply.
    12  It's a Go binary package made available through the Packer plugin SDK
    13  
    14  Say you want to configure the `Config` struct of a `Builder` in a package
    15  located in `my/example-plugin/config.go`. Here are some simple steps you can
    16  follow to make it HCL2 enabled:
    17  
    18  - run `go install github.com/hashicorp/packer-plugin-sdk/cmd/packer-sdc@latest`
    19  
    20  - Add `//go:generate packer-sdc mapstructure-to-hcl2 -type Config` at the top of
    21    `config.go`
    22  
    23  - run `go generate ./my/example-plugin/...`
    24  
    25    This will generate a `my/example-plugin/config.hcl2spec.go` file containing
    26    the configuration fields of `Config`.
    27  
    28  - Make sure that all the nested structs of `Config` are also auto generated the
    29    same way.
    30  
    31  - Now we only need to make your Builder implement the interface by adding the
    32    following snippet:
    33  
    34    ```go
    35    func (b *Builder) ConfigSpec() hcldec.ObjectSpec { return b.config.FlatMapstructure().HCL2Spec() }
    36    ```
    37  
    38    From now on every time you add or change a field of Config you will need to
    39    run the `go generate` command again.
    40  
    41  A good example of this is the [Config struct of the amazon-ebs builder](https://github.com/hashicorp/packer-plugin-amazon/blob/main/builder/ebs/builder.go)