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

时间:2018-04-27 20:52:34

标签: string yaml amazon-cloudformation multiline ref

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

  Resources:
    IdentityPool:
      Type: "AWS::Cognito::IdentityPool"
      Properties:
        IdentityPoolName: ${self:custom.appName}_${self:provider.stage}_identity
        CognitoIdentityProviders:
          - ClientId:
              Ref: UserPoolClient

“AWS :: Cognito :: IdentityPool”的参考返回此资源的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',
      }

我也试过使用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

有什么办法吗?

3 个答案:

答案 0 :(得分:19)

在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}',
      }

答案 1 :(得分:4)

我发现如何使用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}"

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

答案 2 :(得分:1)

使用YAML,您可以简单地编写以下内容:

Outputs:  
  AmplifyConfig:
    Description: key/values to be passed to Amplify.configure(config);
    Value: !Sub '
      {
        "aws_cognito_identity_pool_id": "${IdentityPool}",
        "aws_sign_in_enabled": "enable",
        "aws_user_pools_mfa_type": "OFF",
      }'