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

编写EC2集成SSM的CloudFormation模板时遇Resource Definition is Malformed错误

CloudFormation模板「Resource Definition is Malformed」错误修复方案

你的模板出现该错误,核心是YAML语法不规范、缺失必要配置块导致的,以下是具体问题和修正方案:

错误点分析

  • YAML缩进错误:所有资源(SSMIAMRole、EC2InstanceProfile、Instance)下的Type和Properties未正确缩进,YAML依赖缩进区分层级,错误缩进会导致CloudFormation无法识别资源结构。
  • 缺失Mappings块:模板使用了!FindInMap函数,但未定义对应的EnvironmentToInstanceType映射,无法获取实例类型的对应关系。
  • 缺失Parameters声明:!Ref EnvironmentType引用了未提前声明的参数,必须添加参数定义块。
  • EC2冗余字段:指定SubnetId后无需再设置VPCId,子网已关联到对应VPC,重复指定会引发逻辑冲突。

修正后的完整模板

Description: This Template Create an EC2 in public subnet with SSM.

# 新增:声明EnvironmentType参数
Parameters:
  EnvironmentType:
    Type: String
    Default: dev
    AllowedValues:
      - dev
      - prod
      - test

# 新增:定义实例类型映射
Mappings:
  EnvironmentToInstanceType:
    dev:
      InstanceType: t2.micro
    prod:
      InstanceType: t2.small
    test:
      InstanceType: t2.micro

Resources:
  SSMIAMRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - ec2.amazonaws.com
            Action:
              - sts:AssumeRole
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore

  EC2InstanceProfile:
    Type: AWS::IAM::InstanceProfile
    Properties:
      Path: /
      Roles:
        - !Ref SSMIAMRole

  Instance:
    Type: AWS::EC2::Instance
    Properties:
      IamInstanceProfile: !Ref EC2InstanceProfile
      ImageId: ami-0aa7d40eeae50c9a9
      SubnetId: subnet-0699037225107e8b2
      InstanceType: !FindInMap [EnvironmentToInstanceType, !Ref EnvironmentType, InstanceType]
      Tags:
        - Key: Name
          Value: !Join [ '-', [ !Ref EnvironmentType, webserver ] ]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 10:12:49