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

CloudFormation中Fn::If内使用Fn::Sub报错的解决方案咨询

问题原因及解决方案

错误根源

你遇到的错误是因为Fn::If分支内的!Sub语法使用错误:原本应该将模板字符串和变量映射作为同一个!Sub的参数(数组形式),但你却把它们拆成了数组的两个独立元素。CloudFormation无法识别这种拆分写法,会错误地解析变量部分,导致触发变量名格式校验失败。

修复步骤

将每个Fn::If分支中的!Sub改为数组语法,把Shell脚本模板和变量映射合并到同一个!Sub调用里,同时保持Fn::If的每个分支是单一值。

修正后的代码片段

# accepts a handful of parameters

Conditions:
  IsCleanRegion: !Or
    - !Equals [!Ref "AWS::Region", "us-east-1"]
    - !Equals [!Ref "AWS::Region", "us-east-2"]

Resources: 
  #Creates lambda function
  #creates EC2 SG

  EC2Instance:
    Type: 'AWS::EC2::Instance'
    Properties:
      Tags:
        - Key: Name
          Value: Weather-Website
      ImageId: !FindInMap 
        - RegionToAMIMap
        - !Ref 'AWS::Region'
        - AMI
      InstanceType: t2.micro
      UserData: 
        Fn::Base64:
          Fn::If: 
            - IsCleanRegion
            - !Sub
              - |
                #!/bin/bash
                apt-get update;
                # Some other things, snipped for brevity
                #Some HTML/JS put into a file
                    # Inside HTML/JS File
                    const endpointUrl = '${LambdaFunctionUrl}';
                # More things
              - LambdaFunctionUrl: !GetAtt LambdaUrl.FunctionUrl
            - !Sub
              - |
                #!/bin/bash
                apt-get update;
                # Some other things, snipped for brevity
                #Some HTML/JS put into a file
                    # Inside HTML/JS File
                    const endpointUrl = '${LambdaFunctionUrl}';
                # More things, some differences from the first one
              - LambdaFunctionUrl: !GetAtt LambdaUrl.FunctionUrl
      # finishes up other EC2 Parameters

Outputs:
  #Some Outputs

关键说明

  • 每个!Sub使用!Sub [模板字符串, {变量映射}]的数组语法,确保CloudFormation能正确关联模板中的变量和对应的值。
  • Fn::If的两个分支各自返回一个完整的!Sub结果,而非数组,符合CloudFormation的参数类型要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 19:52:49