How to Add a Self-Referencing Security Group Rule via the AWS CDK

Search for a command to run...

No comments yet. Be the first to comment.
Understanding why new accounts can have a low limit and how to increase it

I'm working with a client to migrate their infrastructure to AWS and apply some modest modernizations during phase 1 of the project. During the migration process, we need to keep their new public endpoints in AWS private during the testing phase. We ...

Solving why AWS Application Migration Service source servers sometimes *disappear*

I recently passed my 5th AWS certification exam, the AWS Security Specialty (SCS). I started on the journey to obtain a substantial collection of AWS certifications back in May 2021. I'm a freelance cloud developer and consultant, focused on building...

If you look at the default VPC in your AWS account, you'll notice there's also a default Security Group. It includes an inbound rule that allows all traffic from itself, a self-referencing rule. This means that any resources with this Security Group attached would be able to communicate with each other over the allowed protocols and ports.

It wasn't immediately obvious to me how to accomplish this via the CDK. It turns out, it's pretty simple. The first argument of the addIngressRule() method on the SecurityGroup takes an IPeer. SecurityGroup implements IPeer, so it is as simple as passing itself in as the first argument.
const selfRefSg = new SecurityGroup(this, "SelfRefSg", {
vpc,
allowAllOutbound: true,
})
selfRefSg.addIngressRule(
selfRefSg,
Port.allTraffic(),
"allow local VPC traffic",
)
After running a cdk deploy:

For a full example, check out the GitHub repo I put together.