useDotenv Understanding

I’m trying to understand how useDotenv really works. It is not clear to me where those env variables are available when you have the useDotenv: true in your serverless.ts. My use case is to use those variable inside the serverless.ts itslef for dynamically create db connections based on .env.{stage} as the blog post states here.

...
useDotenv: true,

...
provider: {
  ...
  stage: '${opt:stage, "development"}',
  ...,
  environment: {
    DB_NAME: '${env:DB_NAME}',
    DB_USER: '${env:DB_USER}',
    DB_PASSWORD: '${env:DB_PASSWORD}',
    READER: '${env:READER}',
    WRITER: '${env:WRITER}',
    DB_PORT: '${env:DB_PORT}',
    AWS_NODEJS_CONNECTION_REUSE_ENABLED: '1',
  }
  ...
}

But I’m getting an error that `Cannot resolve serverless.ts: Variables resolution errored with

Cannot resolve serverless.ts: Variables resolution errored with:
  - Cannot resolve variable at "provider.environment.DB_NAME": Value not found at "env" source,
  - Cannot resolve variable at "provider.environment.DB_USER": Value not found at "env" source,
  - Cannot resolve variable at "provider.environment.DB_PASSWORD": Value not found at "env" source,
  - Cannot resolve variable at "provider.environment.READER": Value not found at "env" source,
  - Cannot resolve variable at "provider.environment.WRITER": Value not found at "env" source,
  - Cannot resolve variable at "provider.environment.DB_PORT": Value not found at "env" source
  • Where do I have access to those variable assuming that the file got loaded and parsed by serverless?
  • If useDotenv doesn’t give access to those variables inside the serverless.ts… Are some solutions that I do have access to those variable?

hi @redeemefy
Where you able to resolve this? I am facing similar issue.

I resolved this by setting useDotenv: true under the service: xxxxxx, and by creating a .env file in the directory containing serverless.yml.