4

从 yml(或 json)模板在 AWS CloudFormation 中创建资源时,是否可以迭代数组以保持模板简短易读。例如,我有一个 Appsync 项目,我必须在其中创建一堆几乎相同的 AWS 类型“AWS::AppSync::Resolver”的解析器。在我与 Cloud Formation 一起使用的 YML 模板中,1 个此类资源可能如下所示

Resource:
 GraphQlAddPostsResolver:
      Type: "AWS::AppSync::Resolver"
      DependsOn: GraphQlSchema
      Properties:
        ApiId:
          Fn::GetAtt: [GraphQlApi, ApiId]
        TypeName: Mutation #<---
        FieldName: addPost #<----
        DataSourceName:
          Fn::GetAtt: [GraphQlLambdaDataSource, Name]
        RequestMappingTemplate: |
          {
              "version" : "2017-02-28",
              "operation": "Invoke",
              "payload": {
                  "field": "addPost", #<---
                  "context": $util.toJson($context)
              }
          }
        ResponseMappingTemplate: |
          $util.toJson($context.result)

我可能有十几个或更多这样的解析器,唯一的区别是我用<----. 有没有办法迭代一组值,比如说

- Field: addPost
  Type: Mutation
- Field: allPosts
  Type: Query
- Field: getPost
  Type: Query
## etc...
4

2 回答 2

7

这在 AWS CloudFormation 中是不可能的。您可以使用嵌套堆栈解决您的问题。使用AWS::CloudFormation::Stack资源。

  FirstResolver:
    Type: AWS::CloudFormation::Stack
    DependsOn: GraphQlSchema
    Properties:
      TemplateURL: ./app-sync-resolver.yml
      Parameters:
        ApiId: !GetAtt GraphQlApi.ApiId
        DataSourceName: !GetAtt GraphQlLambdaDataSource.Name
        Field: addPost
        Type: Mutation

  SecondResolver:
    Type: AWS::CloudFormation::Stack
    DependsOn: GraphQlSchema
    Properties:
      TemplateURL: ./app-sync-resolver.yml
      Parameters:
        ApiId: !GetAtt GraphQlApi.ApiId
        DataSourceName: !GetAtt GraphQlLambdaDataSource.Name
        Field: allPosts
        Type: Query

app-sync-resolver.yml看起来像这样(未经测试!

AWSTemplateFormatVersion: 2010-09-09
Parameters:
  ApiId:
    Type: String
  DataSourceName:
    Type: String
  Type:
    Type: String
  Field:
    Type: String
Resource:
 GraphQLResolver:
      Type: AWS::AppSync::Resolver
      Properties:
        ApiId: !Ref ApiId
        TypeName: !Ref Type
        FieldName: !Ref Field
        DataSourceName: !Ref DataSourceName
        RequestMappingTemplate: |
          {
              "version" : "2017-02-28",
              "operation": "Invoke",
              "payload": {
                  "field": "${Field}",
                  "context": $util.toJson($context)
              }
          }
        ResponseMappingTemplate: |
          $util.toJson($context.result)
于 2018-04-27T13:17:30.840 回答
2

不,你不能。Cloudformation 是一个很棒的工具,但它有其局限性。

你可能想看看 Jinja 或 Troposphere (python)。

于 2018-04-27T13:09:47.200 回答