DEV Community

Ben Ellis
Ben Ellis

Posted on • Originally published at benellis.cloud on

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

Post Cover Image

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.

Screenshot of default security group

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",
)

Enter fullscreen mode Exit fullscreen mode

After running a cdk deploy:

Screenshot of self-referencing rule

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

Top comments (0)