You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在CDK中将指定安全组ID添加到其他安全组的规则中

解决方案

错误原因

你之前使用的ec2.Peer.ipv4()用于传入IPv4 CIDR地址段,ec2.Peer.prefixList()用于传入前缀列表ID,二者均不支持传入安全组ID作为入参,所以配置不生效。

正确实现方式

方式一:直接传入安全组ID

使用CDK内置的ec2.Peer.securityGroupId()方法构造安全组类型的源,这是最简便的实现:

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

const existingSecurityGroupId = "sg-test";

securityGroup.addIngressRule(
    ec2.Peer.securityGroupId(existingSecurityGroupId), // 专门用于传入安全组ID的方法
    ec2.Port.tcp(5432),
    "SecurityGroup of Test"
);

方式二:先导入已有安全组再引用

如果你后续还需要对这个已有的安全组做其他配置,可以先将其导入到当前CDK栈中,再直接作为入站源使用:

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

// 导入已有的安全组到当前栈
const importedSecurityGroup = ec2.SecurityGroup.fromSecurityGroupId(
    this,
    "ImportedTestSG",
    "sg-test"
);

securityGroup.addIngressRule(
    importedSecurityGroup,
    ec2.Port.tcp(5432),
    "SecurityGroup of Test"
);

注意事项

  • 若引用的是其他AWS账户下的安全组,需要补充对端账户ID参数,示例:ec2.Peer.securityGroupId("sg-test", "123456789012"),第二个参数为对端安全组所属的AWS账户ID
  • 若两个安全组不在同一AWS区域,需要先开启安全组跨区域引用功能后再进行配置

内容的提问来源于stack exchange,提问作者Take

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 10:36:04