How to add public subnets to a security group?

Viewed 615

I wrote this code to add public subnets of VPC to a rdsSecurityGroup.

for publicSubnet in self.vpc.public_subnets:
    self.rdsSecurityGroup.add_ingress_rule(peer=publicSubnet,
                                           connection=ec2.Port.tcp(3306))

But I got this error:

jsii.errors.JSIIError: peer.toIngressRuleConfig is not a function

How can I resolve this?

1 Answers

According to https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-security-groups.html#security-group-rules, the source/destination of the security group rule can be one of

  • IP address (range)
  • Security group
  • AWS service prefix

Based on above, you would need to lookup CIDR blocks of your public subnets and add those as your sources for ingress rules. However, it looks like lookup of CIDR blocks of vpc/subnets is not so easy at the moment - https://github.com/aws/aws-cdk/issues/2232. You would need to either remember your CIDR blocks in the code if you are creating the subnets, or have CIDR blocks as a constans in your code in case you are using existing VPC and subnets.

Alternative, perhaps more suitable and convenient is to use security groups as a source for your rules. Add all resources in your public subnets to security groups and manage security group rules based on those.

Related