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

CloudFormation配置EC2启动模板网络接口问题排查

解决AWS CloudFormation中ASG启动模板含网络接口时的安全组配置错误

问题核心

你遇到的错误Invalid launch template: When a network interface is provided, the security groups must be a part of it.,本质是启动模板的配置结构冲突:当你在LaunchTemplateData里定义了NetworkInterfaces节点时,所有安全组必须仅在网络接口的配置内声明,不能在LaunchTemplateData顶层重复设置安全组。

修正方案

  1. 移除LaunchTemplateData顶层的SecurityGroupIds/SecurityGroups字段
  2. 将安全组ID转移到NetworkInterfaces数组内的SecurityGroups列表中
  3. 确保ASG配置中没有额外指定安全组(避免二次冲突)

修正后的完整可复现模板

AWSTemplateFormatVersion: '2010-09-09'
Description: ASG+带网络接口的启动模板(禁用公网IP)

Resources:
  # 实例安全组
  InstanceSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: 实例基础访问控制组
      VpcId: !Ref TargetVPC # 替换为你的VPC ID或引用
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 22
          ToPort: 22
          CidrIp: 192.168.0.0/16 # 按需调整访问范围

  # 带网络接口配置的启动模板
  NoPublicIPLaunchTemplate:
    Type: AWS::EC2::LaunchTemplate
    Properties:
      LaunchTemplateName: NoPublicIP-LT
      LaunchTemplateData:
        InstanceType: t2.micro
        ImageId: ami-0c55b159cbfafe1f0 # 替换为你的区域对应AMI ID
        # 移除顶层安全组设置,移至NetworkInterfaces内
        NetworkInterfaces:
          - DeviceIndex: 0
            AssociatePublicIpAddress: false # 关键:禁用公网IP分配
            SecurityGroups:
              - !Ref InstanceSecurityGroup # 安全组仅在此处声明
            SubnetId: !Ref PublicSubnet # 替换为你的公有子网ID或引用

  # 自动扩缩组
  NoPublicIPASG:
    Type: AWS::AutoScaling::AutoScalingGroup
    Properties:
      AutoScalingGroupName: NoPublicIP-ASG
      MinSize: 1
      MaxSize: 2
      DesiredCapacity: 1
      VPCZoneIdentifier:
        - !Ref PublicSubnet # 部署到指定公有子网
      LaunchTemplate:
        LaunchTemplateId: !Ref NoPublicIPLaunchTemplate
        Version: !GetAtt NoPublicIPLaunchTemplate.LatestVersionNumber

为什么控制台操作可以成功

AWS控制台在编辑启动模板时,会自动检测并修正这种配置冲突:当你添加网络接口配置后,控制台会自动把顶层的安全组设置迁移到网络接口的SecurityGroups列表中,同时移除顶层的重复配置,因此不会触发错误。而CloudFormation是严格按照你编写的配置执行,不会自动修正结构问题,必须手动调整配置逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 15:13:02