At work I spend a lot of time working with AWS CloudFormation. It's a core part of my team's work and forms the backbone of our microservice architecture. I've put together a quick list of some of the slickest features that I'm a fan of that help to make the templates more dynamic/organic assets - they add some spice to the soup.
Conditional resources: by including a
Conditionsfield in any of your template
Resources, you can configure the given resource to not/exist depending on a condition that you define in your
Conditionssection. This can be pretty helpful if you want different resources available in different contexts (e.g. testing vs. development).
Conditional properties: this is similar to #1 above and is similarly useful but focuses on individual properties. For example,
BasePathproperty that you may or may not actually want but AWS requires that it not be set to an empty string. You can combine your condition
Fn::Ifcheck to have an
AWS::NoValuepseudo-parameter that will not create that optional property if the statement evaluates as such.
Nested stacks: separating different resources (particularly in a microservice) is much more easily done by including "parent" stacks to orchestrate the "child" stack microservices. In the
AWS::CloudFormation::Stackcan be defined which adds the "child" to the "parent". Outputs can be shared between the stacks and parameters can be passed directly to the children via the
Parametersproperty. I think of it like function scopes.
Named resources: avoid naming resources and instead refer to their logical names or ARNs where at all possible - explicitly naming them typically results in being unable to launch multiple instances of that resources in the same account as the names will collide (e.g. testing in different stages); a randomly generated ARN won't have this problem but you do need to use
Fn::GetAttto reference it.
- Intrinsic functions: using these liberally can really improve the flexibility and dynamism of your template.
- Custom resources: these are pretty nifty and can be used to automate specific tasks not available in normal template operations, for example loading/backing up databases or Elasticsearch indexes; however, I did find these to be a bit tricky to set up and if you get it wrong they can hang for an hour before finally rolling back.
Descriptions: please, please, please use the
Descriptionattribute wherever you see it - it provides a great deal of context when looking at the console.
- Swagger definitions: using this allows you to offload API Gateway-related resource definitions to a separate file if you want, but you should take a look at a prior post of mine regarding the limitations there.
These are a handful of things that I've found pretty slick while working with CloudFormation templates but I'm sure there are plenty more!