I've created an Advanced CDK course, you can check it out here!

BlogResumeTimelineGitHubTwitterLinkedInBlueSky

The Wrong Way to Use the AWS CDK.

Cover Image for The Wrong Way to Use the AWS CDK.

Last month I wrote about making API calls from within an AWS Cloud Development Kit (CDK) Construct. If you haven't read it yet, please check it out real quick and then come back.

In it, I realized I was doing something wrong. I had some code smell... I had to fake getting async code into the system, by basically ignoring the fact that it was happening at all. It was very powerful and while thinking through the problem it made the most sense to put it close to the Constructs it was driving the creation of.

While it worked, I knew it was flimsy. This couldn't be what the creators intended and my success was coincidental. After a quick chat with someone very familiar with the intent of the CDK, it was confirmed I got lucky.

I don't care if constructors don't let you async/await

So how to make API calls to drive construction?

I knew this was too powerful to do it wrong or stop doing it at all. So a quick little refactoring, pulling the API calls out of the Stack and into the calling code, and it resulted in a nicer result. The `addSnaphots` method is what is making all the API calls now, and not the Stack.

Much better!

In this example I've taken the logic that was determining Snapshots for RDS instances and pulled it into a method run before I even start creating the Stack. Now the Stack has gone back to being deterministic (except for the VPC lookup I also do), and that's a great and important fact. My code (the whole module, my `bin/thing.ts` code) isn't deterministic. But that's fine, the Stack is which means I'm not violating the principles and rules of the API.

This also makes it significantly easier to Unit Test, which is always a good thing. Not that I am, but I should!

Maybe I'll never touch CFN directly again...