serverless-如何动态添加从javascript文件生成的资源并将其与其他资源合并?

问题描述 投票:1回答:1

我想创建一个将Cognito资源部署到AWS的无服务器文件。我有一个config.yml文件,其中包含应在Cognito资源服务器中创建的所有范围。

config.yml

- name: scope1
  description: Description of scope1
- name: scope2
  description: Description of scope2

我想要完成的是为我们注册的每个范围动态生成一个Cognito App客户端,并将这些范围添加到Cognito资源服务器(在我的情况下,已经创建了Cognito用户池和域名)。

为此,我试图制作一个JavaScript文件,该文件将加载config.yml文件并生成两个变量:

  • [userPoolClientList,其中包含Cognito App Client资源的列表。
  • [scopeList,代表应在Cognito资源服务器中注册的范围的列表。

sls-template.js

const fs = require("fs");
const yaml = require("js-yaml");

const scopeList = yaml.safeLoad(fs.readFileSync("config.yml"));

module.exports = {
  scopeList: function () {
    return scopeList.map(({ name, description }) => ({
      ScopeName: name,
      ScopeDescription: description,
    }));
  },

  userPoolClientList: function (serverless) {
    const { cognitoUserPoolId } = serverless.service.custom;

    const scopeResourceList = scopeList.map(({ name, description }) => ({
        [`cognitoUserPoolClient-${name}`]: {
          Type: "AWS::Cognito::UserPoolClient",
          Properties: {
            AllowedOAuthScopes: [`server/${name}`],
            UserPoolId: cognitoUserPoolId,
          },
          DependsOn: "cognitoResourceServer",
        },
    }));

    return Object.assign({}, ...scopeResourceList);
  },
};

现在看起来它返回的正是我想要的(我已经对其进行了测试,并且效果很好)。

我的问题是在serverless.yml文件上的实现以及如何将固定的Resources和动态生成的文件组合在一起。

serverless.yml

resources:
  Resources:
    ${file(sls-template.js):userPoolClientList}
    cognitoResourceServer:
      Type: AWS::Cognito::UserPoolResourceServer
      Properties:
        Identifier: server
        Name: Server
        Scopes: ${file(sls-template.js):scopeList}
        UserPoolId: ${self:custom.cognitoUserPoolId}

这会引发错误,因为语法不正确。但是,当我尝试单独部署资源时(一次仅使用cognitoResourceServer资源,另一次使用javascript文件生成的变量),则一切正常。

问题实际上是我应该如何合并或合并这两个资源。

我一直在尝试许多不同的组合来尝试使其工作,但是它总是给我一个无效的模板。

因此,我想知道我试图在无服务器上实现的目标是否可能,如果可以,如何更改最终的serverless.yml文件以使其正常工作。

非常感谢。

javascript amazon-web-services yaml amazon-cloudformation serverless-framework
1个回答
0
投票

resource blocks can be merged

我相信这应该做到:

resources:
    - Resources: ${file(sls-template.js):userPoolClientList}
    - Resources:
        cognitoResourceServer:
            Type: AWS::Cognito::UserPoolResourceServer
            Properties:
                Identifier: server
                Name: Server
                Scopes: ${file(sls-template.js):scopeList}
                UserPoolId: ${self:custom.cognitoUserPoolId}

不是100%确定动态块是否需要生成Resources顶级密钥,或者是否可以像示例中所示的那样对它进行硬编码。

© www.soinside.com 2019 - 2024. All rights reserved.