Copying and pasting code or configuration comes with a lot of challenges. Fixing a bug requires you to find all the copies to fix them as well. Adding new features to all the copies becomes difficult if copies diverge. That’s why many programming languages allow us to define functions and classes. In CloudFormation, you want to reuse templates as well. Think about a VPC template, database template, load-balanced Fargate container, and so on. Let me introduce CloudFormation Modules. A new feature to reuse CloudFormation templates.
CloudFormation Modules are available since November 2020. A module is a plain CloudFormation template (referred to as a fragment in the docs). To use a module, you have to upload it to the CloudFormation Registry. The CloudFormation CLI helps you with this process. You can define the resource type of your module, but you have to follow the schema
<Organization>::<Service>::<Name>::MODULE. Modules can be nested up to 3 levels deep.
I created a VPC module that I can use like this:
With a concise template, I can create a lot of AWS resources. The template for the VPC module looks like this:
The VPC module includes the subnet module, which demonstrates nested modules.
Unfortunately, there are a ton of limitations. I was struggling to create something useful with CloudFormation Modules. Learn from my experience in the following video.
Source Code: cloudformation-modules.zip
- You can reuse templates by exporting outputs and using them via
Fn::ImportValue: Example: https://github.com/widdix/aws-cf-templates
- Nested stacks can also be helpful. Example: https://github.com/cfn-modules
- Last but not least, preprocessors for CloudFormation such as the AWS CDK or troposphere.