AWS Logo
Menu

To Build or to Reuse? A CDK Question

Learn how to make your architecture more flexible, by optionally reusing existing resources (Code included 😉).

Published Apr 11, 2024
Unless you are starting on a fresh application, the project you are working on will likely have resources already in use. One of the benefits of using CDK over other Infrastructure-as-Code tools is conditionals! Along with the ability to import resources via their ARN, we can create solutions that can use existing resources, or create new ones. This means we can deploy into both fresh and existing environments from the same codebase!

Getting Started

Let’s assume you have a CDK application made and have bootstrapped the target Region & Account. Starting with a new stack, we can begin to scaffold what we’ll need.
Working backward, we’ll say our example use case is to add a new lambda that processes data once it’s dropped in a bucket. For deploying into production, the bucket is already in use and managed by another project. But for the testing environment, there is no bucket. So we will need to make one.
To begin let’s add the lambda, as it’s a constant regardless of where it’s deployed. So the implementation is simple.
Easy enough!
Now onto the juicy stuff. We’ll add a property to the NewStackProps interface to have the bucket ARN supplied externally.
Now armed with the knowledge of “Do we have an existing bucket”, we can either make a new one or reuse the old one.
To wrap up, we’ll add a property to the stack so that the bucket can be referenced elsewhere in the CDK application and hook the lambda up to the bucket so it can process events.

Conclusion

With CDK, it’s possible now more than ever to reuse infrastructure patterns across environments. No matter the state the target environment is in. I would even consider this the tip of the iceberg! To go even further, you could make a custom L3 construct containing the reuse-or-build logic to simplify the process further! The possibilities are endless!

Find me on LinkedIn | Github | Mastodon
 

2 Comments