【问题标题】:altering paths inside serverless artifact更改无服务器工件内的路径
【发布时间】:2016-11-07 10:44:58
【问题描述】:

我的“拓扑”如下:

-- /config/
-- /config/conf1/stage1/config.cfg
-- /config/conf1/stage2/config.cfg
-- /config/conf2/stage1/config.cfg
-- /config/conf2/stage2/config.cfg
-- /lib/
...
-- app.js
-- lambda_function_one.js
-- lambda_function_two.js
   ...
-- config.cfg

我有一个非常适合无服务器的项目 - 节点/lambda。根据需要管理设置阶段和配置,但有一个例外。

我们在项目根目录中使用 config.cfg 进行本地测试,其中包含阶段内的 app.js 和配置文件,用于那些尊重的配置。

这样做的一种方法是将本地配置移动到另一个文件中,然后在打包之前使用 shell 脚本将目标配置复制到项目根目录中。

是否可以指定路径,以便 serverless 从其所在目录获取 config.cfg 并以某种方式将其打包到“项目根目录”中?

谢谢。

【问题讨论】:

    标签: node.js lambda serverless-framework


    【解决方案1】:

    您可能想看看serverless-plugin-write-env-vars。此插件将在部署时创建一个.env 文件,并使用您在serverless.yml 中指定的配置。您仍然可以保留您的configuration in separate files.yml.json)并通过serverless.yml 引用它们。

    例如:

    假设/config/conf1/stage1/config.yml 包括:

    # config.yml
    
    url: https://foo.com
    

    您可以参考serverless.yml

    # serverless.yml
    
    custom:
      myStage: ${opt:stage, self:provider.stage}
      writeEnvVars:
        MY_URL: ${file(./config/conf1/${self:custom.myStage}/config.yml):url}
    
    plugins:
       - serverless-plugin-write-env-vars
    

    对于本地测试,您需要有一个脚本来自己创建.env 文件。一个python示例:

    # test.py
    
    import os.path
    import sys
    import shutil
    
    here = os.path.dirname(os.path.realpath(__file__))
    sys.path.append(os.path.join(here, ".."))
    
    
    def before():
        # copy temp .env to root folder
        dotenv_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '.env_stub')
        global temp_file_path
        temp_file_path = os.path.realpath(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir, '.env'))
        print('Creating ' + temp_file_path + '...')
        shutil.copyfile(dotenv_path, temp_file_path)
    
    
    def after():
        # remove temp .env from root folder
        print('Removing ' + temp_file_path + '...')
        os.remove(temp_file_path)
    
    
    temp_file_path = None
    before()    
    # test ...
    after()
    

    【讨论】:

    • 这是我目前拥有的,或多或少。我的偏好是不必这样做。因此,问题。
    • 那我可能误解了你的问题。你能详细说明吗?你的serverless.yml 在哪里?
    • 我在主目录中有 serverless.yml,另外还有两个“服务”的单独配置文件。我的偏好是自定义打包 zip,而不是复制配置或在 lambda 中构建路径。
    • 我上面的建议不需要您复制配置或从 lambda 构建路径。使用dotenv 创建和加载 .env 后,您可以使用process.env 读取配置
    猜你喜欢
    • 2021-10-04
    • 1970-01-01
    • 2019-04-19
    • 2012-10-01
    • 2014-06-30
    • 1970-01-01
    • 2019-05-17
    • 2017-12-19
    • 1970-01-01
    相关资源
    最近更新 更多