You need to enable JavaScript to run this app. CloudFormation创建CloudWatch Dashboard时DashboardBody报错及Ref参数无效问题
优惠活动
大模型
产品
解决方案
定价
更多

CloudFormation创建CloudWatch Dashboard时DashboardBody报错及Ref参数无效问题

错误原因

你遇到的报错由三个核心问题导致:

  • YAML模板基础语法错误:Parameters节点下所有参数的子属性(Default、Description等)未正确缩进,属于不合法的YAML结构
  • CloudFormation内置函数作用范围问题:Ref写在硬编码的字符串内部时,CloudFormation不会识别执行,只会将其当作普通文本处理,无法完成参数替换
  • DashboardBody的JSON结构本身非法:字符串内部引号未正确转义,末尾多了多余的闭合括号,导致JSON解析失败

修正方案

使用CloudFormation的!Sub函数配合YAML多行文本块构造DashboardBody,不需要手动转义引号,同时可以自动完成参数变量替换。
修正后的完整模板如下:

AWSTemplateFormatVersion: 2010-09-09
Description: "AWS CloudFormation Sample Template for Cloudwatch alert and Dashboard configuration."
Parameters: 
  AlarmNameForCPU: 
    Default: Service_CpuUtilization
    Description: AlarmName
    MaxLength: "99"
    MinLength: "1"
    Type: String
  AlarmNameForMemory: 
    Default: Service_MemoryUtilization
    Description: AlarmName
    MaxLength: "99"
    MinLength: "1"
    Type: String
  DashboardName: 
    Default: ServiceDashboard
    Description: Dashboard
    MaxLength: "99"
    MinLength: "1"
    Type: String
  DashboardTitleCPU: 
    Default: CpuUtilization
    Description: DashboardTitle
    MaxLength: "99"
    MinLength: "1"
    Type: String
  DashboardTitleMemory: 
    Default: MemoryUtilization
    Description: DashboardTitle
    MaxLength: "99"
    MinLength: "1"
    Type: String
Resources:
  Dashboard:
    Type: "AWS::CloudWatch::Dashboard"
    Properties:
      DashboardName: !Ref DashboardName
      DashboardBody: !Sub |
        {
          "widgets": [
            {
              "height": 3,
              "width": 9,
              "y": 0,
              "x": 0,
              "type": "metric",
              "properties": {
                "title": "${DashboardTitleCPU}",
                "annotations": {
                  "alarms": [
                    "arn:aws:cloudwatch:us-east-1:468491150671:alarm:${AlarmNameForCPU}"
                  ]
                },
                "view": "singleValue"
              }
            },
            {
              "height": 3,
              "width": 9,
              "y": 0,
              "x": 9,
              "type": "metric",
              "properties": {
                "title": "${DashboardTitleMemory}",
                "annotations": {
                  "alarms": [
                    "arn:aws:cloudwatch:us-east-1:468491150671:alarm:${AlarmNameForMemory}"
                  ]
                },
                "view": "singleValue"
              }
            }
          ]
        }

如果你的账号ID或者区域不是固定值,也可以用AWS::AccountId、AWS::Region伪参数替换硬编码的468491150671和us-east-1,实现模板跨账号跨区域复用。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 02:30:02