Add Ingress Rule to Security Groups using AWS CDK

I got the following to work using TS, hope it helps some.

const mySG = new ec2.SecurityGroup(this, `${stack}-security-group`, {
    vpc: vpc,
    allowAllOutbound: true,
    description: 'CDK Security Group'
});

mySG.addIngressRule(ec2.Peer.anyIpv4(), ec2.Port.tcp(22), 'SSH frm anywhere');
mySG.addIngressRule(ec2.Peer.ipv4('10.200.0.0/24'), ec2.Port.tcp(5439), 'Redshift Ingress1');
mySG.addIngressRule(ec2.Peer.ipv4('10.0.0.0/24'), ec2.Port.tcp(5439), 'Redshift Ingress2');

Btw, it is not recommended to use an explicit security group name: https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ec2.SecurityGroup.html


In SDK documentation: "Direct manipulation of the Security Group through addIngressRule and addEgressRule is possible, but mutation through the .connections object is recommended. If you peer two constructs with security groups this way, appropriate rules will be created in both."

So it's better to add rules like this:

sg.connections.allow_from(
  Peer.any_ipv4(),
  Port.tcp(22),
  "ssh" 
)

Tags:

Python

Aws Cdk