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

使用AWS CDK连接EFS到EC2时出现Security Group Rules未定义错误

解决AWS CDK中EFS连接EC2实例时的_securityGroupRules未定义错误

问题根源

你使用了AWS CDK的**L1构造ec2.CfnInstance**创建EC2实例,而fs.connections.allow_default_port_from()方法依赖实现IConnectable接口的L2构造(如ec2.Instance)。L1构造仅对应CloudFormation原生资源,未封装完整的Connections对象逻辑,因此触发Cannot read properties of undefined (reading '_securityGroupRules')错误。


解决方案一:改用L2构造ec2.Instance创建EC2实例

L2构造ec2.Instance封装了完整的连接管理能力,可直接与EFS的connections方法兼容。修改后的实例创建代码如下:

# 替换原CfnInstance代码
instance = ec2.Instance(stack, cdk.Stack.of(stack).stack_name,
    key_name="key-name",
    vpc=ec2.Vpc.from_lookup(stack, "vpc-123"),
    vpc_subnets=ec2.SubnetSelection(subnet_ids=["subnet-123"]),
    security_group=ec2.SecurityGroup.from_security_group_id(stack, "sg", "sg-123"),
    instance_profile=ec2.InstanceProfile.from_instance_profile_name(stack, "profile", "profile-name"),
    instance_type=ec2.InstanceType("t3.medium"),
    machine_image=ec2.MachineImage.generic_linux({"us-east-1": "ami-08d4ac5b634553e16"}),
    block_devices=[ec2.BlockDevice(
        device_name="/dev/sda1",
        volume=ec2.BlockDeviceVolume.ebs(12, delete_on_termination=True, volume_type=ec2.EbsDeviceVolumeType.GP3)
    )],
    user_data=ec2.UserData.custom(init_script.render()),
    tags={
        "Name": cdk.Stack.of(stack).stack_name
    }
)

# 原EFS连接代码可正常使用
fs.connections.allow_default_port_from(instance)

解决方案二:若必须使用L1构造,手动添加安全组规则

如果业务场景要求必须使用ec2.CfnInstance,可跳过connections方法,直接创建CloudFormation安全组入站规则允许EFS端口访问:

# 手动添加EFS安全组入站规则,允许EC2实例的安全组访问2049端口
ec2.CfnSecurityGroupIngress(stack, "EfsIngressFromEc2",
    group_id=fs.security_group.security_group_id,
    ip_protocol="tcp",
    from_port=2049,
    to_port=2049,
    source_security_group_id="sg-123"  # EC2实例使用的安全组ID
)

注意事项

  • 确保EC2实例和EFS文件系统处于同一VPC下,子网可用区匹配
  • 安全组sg-123需允许EC2实例出站访问2049端口(若未配置默认规则)
  • 用户数据中需包含EFS挂载脚本(参考官方文档中的挂载步骤)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 05:20:26