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

AWS CDK中如何将Fargate服务转为IPeer添加到IngressRule

AWS CDK Fargate服务配置数据库安全组入站规则实现方法

问题原因

ec2.SecurityGroup的addIngressRule方法要求传入实现IPeer接口的对象作为访问源,FargateService实例本身不直接实现IPeer接口,无法直接作为参数传入。

解决方案

你不需要手动做类型转换,有两种符合规范的写法:

  • 直接使用你创建Fargate服务时预先绑定的adminServiceSg安全组作为访问源(和你现有代码逻辑最匹配,写法最简洁)
    修正后的入站规则配置代码如下:
    const ecsAdminService = new ecs.FargateService(this, "AdminService", {
      cluster,
      taskDefinition:taskDefinitionAdmin,
      desiredCount: desiredCount,
      vpcSubnets: props!.vpc.selectSubnets({ subnetType: ec2.SubnetType.PUBLIC }),
      assignPublicIp: true, 
      securityGroups:[adminServiceSg],
      enableExecuteCommand:true,
      serviceName: serviceName
    });
    
    // 直接传入服务绑定的安全组作为访问源
    props!.dbSecurityGroup.addIngressRule(
      adminServiceSg,
      ec2.Port.tcp(3306),
      'allow mysql port from admin fargate service'
    );
    
  • 如果创建Fargate服务时没有手动指定安全组、由CDK自动生成默认安全组,可以通过服务实例的connections属性获取关联的安全组传入:
    props!.dbSecurityGroup.addIngressRule(
      ecsAdminService.connections.securityGroups[0],
      ec2.Port.tcp(3306),
      'allow mysql port from admin fargate service'
    );
    

配置说明

  • 该配置的生效逻辑是:所有绑定了adminServiceSg安全组的资源(即你部署的Admin Fargate服务任务),都可以通过TCP 3306端口访问绑定了数据库安全组的数据库实例
  • 注意不要因为Fargate任务配置了公网IP就直接将0.0.0.0/0加入数据库入站规则,会造成公网暴露的安全风险

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 16:06:25