Skip to content

Instantly share code, notes, and snippets.

@tuxinaut
Last active March 23, 2023 08:00
Show Gist options
  • Save tuxinaut/35e89e8f8bf89ed47abc796b8fe5d514 to your computer and use it in GitHub Desktop.
Save tuxinaut/35e89e8f8bf89ed47abc796b8fe5d514 to your computer and use it in GitHub Desktop.
AWS CDK self referencing security group
sg = ec2.CfnSecurityGroup(self, "sample-sg",
group_description="Allows traffic to the database when attached",
vpc_id=vpc.vpc_id,
)
ingress = ec2.CfnSecurityGroupIngress(self, "sample-sg-ingress",
group_id=sg.attr_group_id,
source_security_group_id=sg.attr_group_id,
ip_protocol="TCP",
description="Self referencing SG rule to allow TCP traffic on port 3306",
from_port=3306,
to_port=3306,
)
# This is the important part
# If the dependency is not set CloudFormation will complain that the security group does not exist
# Unfortunately I only made it work with CloudFormation Resources because the normal classes do not
# support add dependies
ingress.add_depends_on(sg)
@klang
Copy link

klang commented Apr 12, 2022

This has probably changed since you wrote this gits, but I stumbled upon your code in my hunt for a solution.

 sg = ec2.SecurityGroup(self, "sample-sg", vpc=vpc.vpc_id)
 sg.add_ingress_rule(sg, ec2.Port.tcp(3306))

A Security Group implements IPeer and can therefore be used as the first element in add_ingress_rule.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment