How to access environment variables and pass to Lambda function using useDotenv: true option in serverless.yml?

Viewed 1087

I am trying to pass environment variables to my Lambda function in serverless.yml (version 2.32.0) but I am not sure the way of doing it. The doucmentaiton: https://www.serverless.com/framework/docs/environment-variables/ doesn't mention how to. Right now, I am using the useDotenv: true option and then trying to access the environment variables by ${process.env.ENV1} but it is not working. Below is my serverless.yml file:

serverless.yml

service: service-name
frameworkVersion: "2.32.0"
useDotenv: true

provider:
  name: aws
  versionFunctions: false
  runtime: nodejs12.x
  region: <region>
  stage: dev
  profile: default

functions:
  function-name:
    handler: handler
    timeout: 120
    environment:
      ENV1: ${process.env.ENV1}
      ENV2: ${process.env.ENV2}
      ENV3: ${process.env.ENV3}

I am getting no errors or warning when I run sls deploy but the environment variables are not being uploaded. How would I be able to do it?

1 Answers

Okay I got it by replacing process.env. with env:

serverless.yml:

service: service-name
frameworkVersion: "2.32.0"
useDotenv: true

provider:
  name: aws
  versionFunctions: false
  runtime: nodejs12.x
  region: <region>
  stage: dev
  profile: default

functions:
  function-name:
    handler: handler
    environment:
      ENV1: ${env:ENV1}
      ENV2: ${env:ENV2}
      ENV3: ${env:ENV3}
    timeout: 120
Related