Search code examples
amazon-web-servicesaws-lambdaserverless-frameworkserverless

Serverless lambda Global Environmental Variables


I am playing with serverless, and I am trying to figure out how to rewrite this serverless.yml file so I don't duplicate the environmental variables for each function. Is there a way to set environmental variables globally?

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}

Solution

  • You just simply move them into the provider section. They will be applied to all functions in the same service.

    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