June 20-22 Announcing HashiConf Europe full schedule: keynotes, sessions, labs & more Register Now
  • Infrastructure
    • terraform
    • packer
  • Networking
    • consul
  • Security
    • vault
    • boundary
  • Applications
    • nomad
    • waypoint
    • vagrant
  • HashiCorp Cloud Platform

    A fully managed platform to automate infrastructure on any cloud with HashiCorp products.

    • consul
    • terraform
    • vault
    • packerbeta
    Visit cloud.hashicorp.com
  • Overview
  • Tutorials
  • Docs
  • Plugins
  • Community
GitHubInstall PackerTry HCP Packer
    • v1.8.x (latest)
    • v1.7.x
    • v1.6.x
    • v1.5.x
  • Upgrade Your Plugin to use the Packer plugin sdk
  • Upgrade Your Template to use Packer init
    • Overview
    • Variables
    • Upgrade Packer JSON Template to HCL2
    • Making a plugin HCL2 enabled
    • Overview
    • Unattended Installation for Windows
    • Unattended Installation for Debian
    • Overview
    • Build Images in CI/CD
    • Build a VirtualBox Image with Packer in TeamCity
    • Pipelineing Builds
    • Trigger Terraform Enterprise runs
    • Upload a VirtualBox Image to S3
Type '/' to Search

»Auto Generate the HCL2 code of a plugin

From v1.5, Packer can be configured using HCL2. Because Packer has so many 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 made available through the Packer plugin SDK

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:

  • run go install github.com/hashicorp/packer-plugin-sdk/cmd/packer-sdc@latest

  • Add //go:generate packer-sdc mapstructure-to-hcl2 -type Config at the top of config.go

  • run go generate ./my/example-plugin/...

    This will generate a my/example-plugin/config.hcl2spec.go file containing the configuration fields of Config.

  • Make sure that all the nested structs of Config are also auto generated the same way.

  • Now we only need to make your Builder implement the interface by adding the following snippet:

    func (b *Builder) ConfigSpec() hcldec.ObjectSpec { return b.config.FlatMapstructure().HCL2Spec() }
    
    func (b *Builder) ConfigSpec() hcldec.ObjectSpec { return b.config.FlatMapstructure().HCL2Spec() }
    

    From now on every time you add or change a field of Config you will need to run the go generate command again.

A good example of this is the Config struct of the amazon-ebs builder

github logoEdit this page
IntroGuidesDocsCommunityPrivacySecurityPress KitConsent Manager