You need to enable JavaScript to run this app. AWS CloudFormation的Fn::ImportValue搭配!Join报错如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

AWS CloudFormation的Fn::ImportValue搭配!Join报错如何解决?

CloudFormation Fn::ImportValue 验证错误解决方案

问题场景

我在CloudFormation模板中定义了创建监听器规则的资源,期望根据传入的EnvironmentType参数和AWS区域,从已导出对应值的CloudFormation栈中导入监听器ARN,初始模板代码如下:

Parameters:
  EnvironmentType:
    Type: String
    Default: "sandbox"
  ECSClusterStackNameParameter:
    Type: String
    Default: "ECS-US-Sandbox"

Mappings:
  production:
    us-east-1:
      stackWithAlbListenerInfo: "ECS-US-Prod"
    eu-north-1:
      stackWithAlbListenerInfo: "ECS-EU-Prod"
  staging:
    us-east-1:
      stackWithAlbListenerInfo: "ECS-US-Staging"
    eu-north-1:
      stackWithAlbListenerInfo: ""
  sandbox:
    us-east-1:
      stackWithAlbListenerInfo: "ECS-US-Sandbox"
    eu-north-1:
      stackWithAlbListenerInfo: ""

Conditions:
  StackExists:
    !Not [ !Equals [ !FindInMap [ !Ref EnvironmentType, !Ref "AWS::Region", stackWithAlbListenerInfo ], ""] ]

Resources:
  AlbListenerRule:
    Type: AWS::ElasticLoadBalancingV2::ListenerRule
    Condition: UseListenerRule
    Properties:
      ListenerArn:
        !If
          - StackExists
          -
            - Fn::ImportValue:
                !Join
                  - "-"
                  - - !FindInMap [ !Ref EnvironmentType, !Ref "AWS::Region", stackWithAlbListenerInfo ]
                    - "ListenerArn"
          - Fn::ImportValue:
              - !Sub "${ECSClusterStackNameParameter}-ListenerArn"

报错信息

模板提交验证时返回如下错误:

ERROR: Service: marcom-stats-service, cfnUpdate error: com.amazonaws.services.cloudformation.model.AmazonCloudFormationException: Template error: the attribute in Fn::ImportValue must be a string or a function that returns a string (Service: AmazonCloudFormation; Status Code: 400; Error Code: ValidationError; Request ID: 2678552e-cf6c-46e1-b640-a7c07de385c2; Proxy: null)

错误原因

初始写法在!If的第一个匹配分支中,多套了一层不必要的数组层级,导致Fn::ImportValue接收的输入不是字符串类型,触发验证失败。同时原逻辑的分支判断写法冗余,可以进一步优化。

正确写法

优化后的模板片段如下,既解决了验证报错,也匹配实际业务逻辑:

AlbListenerRule:
    Type: AWS::ElasticLoadBalancingV2::ListenerRule
    Condition: UseListenerRule
    Properties:
      ListenerArn:
        Fn::ImportValue: !Sub
          - ${StackName}-ListenerArn
          - { StackName: !If [ StackExists, !FindInMap [ !Ref EnvironmentType, !Ref "AWS::Region", stackWithAlbListenerInfo ], !Ref ECSClusterStackNameParameter ] }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 10:27:08