November 15, 2020

CDK Escape Hatches

I’ve been starting to use CDK over the last few months. It’s a really powerful way to describe your infrastructure. I’m specifically been using Python, so much of what I discuss here will be in Python where I need to reference languages.

One of the things that I really liked about it, is that creating MVPs or PoCs can be really quick as there are high level constructs available out of the box. An example is the AutoScalingGroup construct. When building an AutoSacling Group in traditional CloudFormation you need to define a Launch Configuration and then reference this in your AutoScaling Group.

With the AutoScaling Group high level construct in CDK there is no need to build and reference a Launch Configuration. But, this has implications.

What happens, when you need to do something special in your Launch Configuartion?

In the CDK you can use connections to add TCP or UDP based rules to a Security Group that is automatically created in your AutoScalingGroup construct and is defined in your Launch Configuration. This is great, until you have that one weird use case that needs to use a protocol other than TCP or UDP. Sometimes you have applications that might require esoteric protocols and one such example that I had recentlys is the use of an older IPSEC that requires AH and ESP (protocols 50 and 51) to be open.

This required the creation of a unique Security Group, but how could I attach it? This is where Escape Hatches can come in handy.

In true AWS style, the documentation is great… to a point. Digging a bit futher you can find that there is a findChild method on the default ConstuctNode class. The problem here is that you have no idea what the nodes are called, and need to dig into the code (or guess) to find this out.

I did a bit of both with my adventure finding the LaunchConfiguration child in the AutoScalingGroup construct. Pretty boring, but the team called it LaunchConfig and you can see that defined in the source code.

This means that you can now do something like the following to configure a custom Security Group:

        lc = myasg.node.find_child('LaunchConfig')
        lc.security_groups = [sg.attr_group_id]

It’s not quite as elegant as connections, because there is a whole stack of code you don’t see here, that is building a Security Group from first principles, which kind of defeats the point CDK.

And of course, since I implemented this, there is now a way you can define your own Security Group.

It’s always the way. But if you ever need to use Escape Hatches you can see how simple it is.

Happy CDKing.

© Greg Cockburn

Powered by Hugo & Kiss.