Home > front end >  How do you add security group ID to other security group in CDK?
How do you add security group ID to other security group in CDK?

Time:11-02

const securityGroup = new ec2.SecurityGroup(this, "Ec2SecurityGroup", {
    vpc,
});

const securityGroupId = "sg-test";

securityGroup.addIngressRule(
    // doesn't work
    ec2.Peer.ipv4(securityGroupId),
    // doesn't work
    ec2.Peer.prefixList(securityGroupId),
    ec2.Port.tcp(5432),
    "SecurityGroup of Test"
);

I want to add an ID of security group but it seems like it's impossible...

CodePudding user response:

Start by looking at the documentation:

https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ec2.SecurityGroup.html

As yoou can see, you can pass a SecurityGroup to the peer attribute.

To create a SecurityGroup from its ID, use SecurityGroup.fromSecurityGroupId:

const securityGroup = new ec2.SecurityGroup(this, "Ec2SecurityGroup", {
    vpc,
});

const otherSecurityGroup = ec2.SecurityGroup.fromSecurityGroupId(
    this,
    "OtherSecurityGroup",
    "sg-test"
);

securityGroup.addIngressRule(
    otherSecurityGroup,
    ec2.Port.tcp(5432),
    "SecurityGroup of Test"
);
  • Related