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

CloudFormation YAML模板If Else不生效,如何添加通用IP避免代码重复

问题原因

你调整后的写法不符合CloudFormation YAML语法规范:SecurityGroupIngress字段要求值为安全组规则的列表结构,你直接在固定规则后拼接!If条件函数属于语法错误,CloudFormation无法自动将!If返回的规则列表和你写的固定规则做合并。

解决方案

方案1(推荐,CloudFormation 2023及以上版本支持)

使用内置的!Concat函数实现列表拼接,通用IP规则仅需编写一次,无需重复拷贝:

SecurityGroupIngress: !Concat
  # 通用IP规则(所有场景生效,仅需编写一次)
  - - Description: "Its *All* fruits IPs"
      FromPort: X
      ToPort: X
      IpProtocol: tcp
      CidrIp: X.X.X.X
  # 条件分支返回对应场景的专属规则
  - !If
    - IsApple
    - - Description: "Its Apple IP"
        FromPort: X
        ToPort: X
        IpProtocol: tcp
        CidrIp: X.X.X.X
    - - Description: "It's not Apple IP"
        FromPort: X
        ToPort: X
        IpProtocol: tcp
        CidrIp: X.X.X.X

!Concat会自动将两个列表拼接为一个,最终生成的规则列表同时包含通用规则和对应场景的专属规则,完全符合需求。

方案2(全版本兼容)

如果你的模板需要兼容旧版本CloudFormation,可以将通用规则存放在Mappings中统一管理,两个分支直接引用即可,无需重复编写:

# 模板顶层定义通用规则映射,仅需编写一次
Mappings:
  CommonSGRules:
    AllFruits:
      Description: "Its *All* fruits IPs"
      FromPort: X
      ToPort: X
      IpProtocol: tcp
      CidrIp: X.X.X.X

Resources:
  你的安全组资源ID:
    Type: AWS::EC2::SecurityGroup
    Properties:
      # 其余安全组配置省略
      SecurityGroupIngress: !If
        - IsApple
        - - !FindInMap [CommonSGRules, AllFruits]
          - Description: "Its Apple IP"
            FromPort: X
            ToPort: X
            IpProtocol: tcp
            CidrIp: X.X.X.X
        - - !FindInMap [CommonSGRules, AllFruits]
          - Description: "It's not Apple IP"
            FromPort: X
            ToPort: X
            IpProtocol: tcp
            CidrIp: X.X.X.X

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 22:36:03