Cloudformation Conditionals - how to DRY?
This seems like a larger structural problem in cloudformation which maybe doesn't have an answer, but I thought I'd check and see if anyone's found a better way to do this.
As a simple example, consider a template with a load balancer that has a target group with two EC2 instances behind it. Now, let's say I only want two instances sometimes, so I put a Conditional on one instance.
The rub is that now I need to copy-paste the entire chain of load balancer resources and tweak the copy to only have one backend. Then I have to apply conditionals to both sets of load balancer config so that only one set gets created.
This is a ton of copy-pasted code and it's really bad for reliability. The intuitive way this should work is just doing some kind of !If on the target group to either have one or two instances, but it looks like Cloudformation only supports "If" in the form of Conditionals on resources.
Is there a better way?
Posted Sep 20, 2019, 9:14 PM UTC
I'm not sure I understand your question, but if you want to build logic into a template Cloudformation isn't really the tool for the job since it's primary function is to be declarative.
If you want evaluative IaC I'd suggest you either look into Terraform or the CDK, which supports evaluation. If you're heavily invested in Cloudformation perhaps CDK is preferable.
https://docs.aws.amazon.com/cdk/latest/guide/constructs.html
https://blog.gruntwork.io/terraform-up-running-2nd-edition-early-release-is-now-available-b104fc29783f#da95
Yeah, Terraform I've used in the past pretty well. We're very heavy into CF at this point though. The CDK stuff looks interesting. I think that's still too big of a change for what I'd consider a small problem, but I'll keep it in mind.
Troposphere may be of interest to you. You can use the full power of python and get loops, if-thens, etc. And let it spit out a static JSON file which you then deploy to CFN.
That's an interesting option, thanks!