无服务器 lambda 全局环境变量

Serverless lambda Global Environmental Variables

我正在玩无服务器,我正在尝试弄清楚如何重写这个 serverless.yml 文件,这样我就不会为每个函数复制环境变量。有没有办法全局设置环境变量?

service: test-api
frameworkVersion: ">=1.2.0 <2.0.0"
provider:
  name: aws
  runtime: nodejs12.x
  timeout: 30
  stage: dev
  memorysize: 2048
  region: us-east-2
  logRetentionInDays: 21

functions:
  doCreate:
    handler: functions/do-create.handler
    environment:
      DB_PORT: ${ssm:/${self:custom.stage}/db_port}
      DB_URL: ${ssm:/${self:custom.stage}/db_url}
      API_KEY: ${ssm:/${self:custom.stage}/api_key}
      ENV: "${self:custom.stage}"
      SEARCH_ARN: ${ssm:/${self:custom.stage}/search_arn}
  doUpdate:
    handler: functions/do-update.handler
    environment:
      DB_PORT: ${ssm:/${self:custom.stage}/db_port}
      DB_URL: ${ssm:/${self:custom.stage}/db_url}
      API_KEY: ${ssm:/${self:custom.stage}/api_key}
      ENV: "${self:custom.stage}"
      SEARCH_ARN: ${ssm:/${self:custom.stage}/search_arn}

使用 SAM 模板中的全局部分

Globals:
  Function:
    Runtime: nodejs12.x
    Timeout: 180
    Handler: index.handler
    Environment:
      Variables:
        TABLE_NAME: data-table

更多详情请阅读本文档https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-specification-template-anatomy-globals.html

您只需将它们移至 provider 部分即可。它们将应用于同一服务中的所有功能。

service: test-api
frameworkVersion: ">=1.2.0 <2.0.0"
provider:
  name: aws
  runtime: nodejs12.x
  timeout: 30
  stage: dev
  memorysize: 2048
  region: us-east-2
  logRetentionInDays: 21
  environment:
    DB_PORT: ${ssm:/${self:custom.stage}/db_port}
    DB_URL: ${ssm:/${self:custom.stage}/db_url}
    API_KEY: ${ssm:/${self:custom.stage}/api_key}
    ENV: "${self:custom.stage}"
    SEARCH_ARN: ${ssm:/${self:custom.stage}/search_arn}
functions:
  doCreate:
    handler: functions/do-create.handler
  doUpdate:
    handler: functions/do-update.handler