Pitfalls and things to avoid
A lot of example templates in GitHub and community resources only build one item at a time. It’s actually more helpful to build everything you can in one template and run just the builds you need. Unfortunately, Packer doesn’t combine all HCL files or all files in the current directory as Terraform does. This means you need to put all sources and build combinations in one file, which can be problematic as templates grow. Unfortunately, you also can’t include or refer to other templates, which might distribute complexity among other files. What you can do is make use of HCL2’s language features.
Luckily, there are a few tools that HCL2 or JSON in Packer 1.7+ give you to simplify complex builds. Dynamic features aren’t available in JSON templates, but you can actually use the HCL2 for_each
construct. for_each
in HCL2 isn’t quite like any other foreach
in a language you’ve used before. HCL2’s for_each...