在Cloudformation YAML中,在多行字符串中使用Ref(?使用Fn:Sub)

hon*_*let 8 string yaml ref multiline aws-cloudformation

想象一下,你有一个aws资源,如

  Resources:
    IdentityPool:
      Type: "AWS::Cognito::IdentityPool"
      Properties:
        IdentityPoolName: ${self:custom.appName}_${self:provider.stage}_identity
        CognitoIdentityProviders:
          - ClientId:
              Ref: UserPoolClient
Run Code Online (Sandbox Code Playgroud)

"AWS :: Cognito :: IdentityPool"的Ref返回此资源的id.现在假设我想在多行字符串中引用该id.我试过了

Outputs:  
  AmplifyConfig:
    Description: key/values to be passed to Amplify.configure(config);
    Value: |
      {
        'aws_cognito_identity_pool_id': ${Ref: IdentityPool}, ##<------ Error
        'aws_sign_in_enabled': 'enable',
        'aws_user_pools_mfa_type': 'OFF',
      }
Run Code Online (Sandbox Code Playgroud)

我也尝试过使用Fn:Sub但没有运气.

   AmplifyConfig:
      Description: key/values to be passed to Amplify.configure(config);
      Value: 
        Fn::Sub 
          - |
            {
              'aws_cognito_identity_pool_id': '${Var1Name}',
              'aws_sign_in_enabled': 'enable',
            }
          - Var1Name:
              Ref: IdentityPool
Run Code Online (Sandbox Code Playgroud)

有什么办法吗?

Clo*_*hel 21

|在YAML中使用管道符号会将以下所有缩进行转换为多行字符串.

一个管道,结合使用!Sub将让你使用:

  • 您的资源Ref返回值很容易就像${YourResource}
  • 他们的Fn::GetAtt回报价值只有一段时间${YourResource.TheAttribute}
  • 任何伪参数都是这样的 ${AWS:region}

一样简单!Sub |,跳到下一行并添加适当的缩进.例:

Resources:
  YourUserPool:
    Type: AWS::Cognito::UserPool
    Properties:
      UserPoolName: blabla

Outputs:
  AmplifyConfig:
    Description: key/values to be passed to Amplify.configure(config);
    Value: !Sub |
      {
        'aws_cognito_identity_pool_id': '${YourUserPool}',
        'aws_sign_in_enabled': 'enable',
        'aws_user_pools_mfa_type': 'OFF',
      }
  AdvancedUsage:
    Description: use Pseudo Parameters and/or resources attributes
    Value: !Sub |
      {
        'aws_region': '${AWS::Region}',
        'user_pool_arn': '${YourUserPool.Arn}',
      }
Run Code Online (Sandbox Code Playgroud)


hon*_*let 5

我发现了如何使用 Join 做到这一点

AmplifyConfig:
  Description: key/values to be passed to Amplify.configure(config);
  Value:
    Fn::Join:
      - ''
      - - "{"
        - "\n  'aws_cognito_identity_pool_id':"
        - Ref : IdentityPool
        - "\n  'aws_user_pools_id':"
        - Ref : UserPool
        - "\n  'aws_user_pools_web_client_id':"
        - Ref : UserPoolClient
        - ",\n  'aws_cognito_region': '${self:provider.region}'"
        - ",\n  'aws_sign_in_enabled': 'enable'"
        - ",\n  'aws_user_pools': 'enable'"
        - ",\n  'aws_user_pools_mfa_type': 'OFF'"
        - "\n}"
Run Code Online (Sandbox Code Playgroud)

这有效,但有点丑陋。我将暂时不接受这个答案,看看是否有人可以展示如何使用 Fn::Sub 做到这一点。

  • 考虑通过转换已接受的答案来给予 Clorichel 的解决方案功劳 (4认同)