Giter Club home page Giter Club logo

serverless-dotenv-plugin's Introduction

serverless-dotenv-plugin

CI Coverage Status npm version

Preload function environment variables into Serverless. Use this plugin if you have variables stored in a .env file that you want loaded into your functions.

This used to also preload environment variables into your serverless.yml config, but no longer does with serverless>=2.26.0. See this discussion thread or the FAQ below for details on the impact of how environment variables are loaded with serverless>=2.26.0 and serverless>=3.0.0.**

Do you need this plugin?

Serverless Framework can now natively resolve ${env:xxx} variables from .env files by setting useDotenv: true in the configuration:

useDotenv: true

provider:
  environment:
    FOO: ${env:FOO}

For more complex situations, you will need to wire up dotenv yourself.

This plugin is only useful if you want to automatically import all variables from .env into functions:

plugins:
  - serverless-dotenv-plugin

provider:
  environment:
    # With the plugin enabled, all variables in .env are automatically imported

Install and Setup

First, install the plugin:

> npm i -D serverless-dotenv-plugin

Next, add the plugin to your serverless config file:

service: myService
plugins:
  - serverless-dotenv-plugin
...

Now, just like you would using dotenv in any other JS application, create your .env file in the root of your app:

DYNAMODB_TABLE=myTable
AWS_REGION=us-west-1
AUTH0_CLIENT_ID=abc12345
AUTH0_CLIENT_SECRET=12345xyz

When deploying, all the variables listed in .env will automatically be available in the deployed functions.

Automatic ENV File Resolution

By default, the plugin looks for the file: .env. In most use cases this is all that is needed. However, there are times where you want different env files based on environment. For instance:

.env.development
.env.production

When you deploy with NODE_ENV set: NODE_ENV=production sls deploy the plugin will look for files named .env, .env.production, .env.production.local. If for some reason you can't set NODE_ENV, you could always just pass it in as an option: sls deploy --env production or sls deploy --stage production. If NODE_ENV, --env or --stage is not set, it will default to development.

DEPRECATION WARNING: as of serverless>=3.0.0, --env will not be supported due to changes to the Serverless Framework. See FAQ for details.

The precedence between the options is the following: NODE_ENV > --env > --stage

The env resolution pattern follows the one used by Rail's dotenv and create-react-app

Valid .env file names Description
.env Default file, always included
.env.local Included in all environments except test
.env.development If NODE_ENV or --env or --stage is not set, will try to load .env.development.
.env.{ENV} If NODE_ENV or --env or --stage is set, will try to load .env.{env}.
.env.{ENV}.local Every env set up in .env.{ENV}.local will override other envs

Note: .env, .env.development, and .env.production files should be included in your repository as they define defaults. .env*.local should be added to .gitignore, as those files are intended to be ignored. .env.local is where secrets can be stored.

Lambda Environment Variables

Again, remember that when you deploy your service, the plugin will inject these environment vars into every lambda functions you have and will therefore allow you to reference them as process.env.AUTH0_CLIENT_ID (Nodejs example). If this behaviour is not desireable, set include to [].

Plugin options

All options are optional.

custom:
  dotenv:
    # default: project root
    path: path/to/my/dotenvfiles

    # if set, ignores `path` option, and only uses the dotenv file at this location
    # basePath: path/to/my/.env

    # if set, uses provided dotenv parser function instead of built-in function
    dotenvParser: dotenv.config.js

    # default: adds all env variables found in your dotenv file(s)
    # this option must be set to `[]` if `provider.environment` is not a literal string
    include:
      - DDB_TABLE
      - S3_BUCKET

    # default: does not exclude any env variables found in your dotenv file(s)
    # does nothing if `include` is set
    exclude:
      - AWS_ACCESS_KEY_ID
      - AWS_SECRET_ACCESS_KEY
      - AWS_SESSION_TOKEN
      - NODE_ENV              # Can not be declared for Google Cloud Functions

    # defaults to `true`
    logging: false

    # default: plugin does not cause an error if any file or env variable is missing
    required:
      # default: []
      env:
        - API_KEY

      # default: false
      file: true

    # default: true
    variableExpansion: false
  • path (string)

    • The plugin will look for your .env file in the same folder where you run the command using the file resolution rules as described above, but these rules can be overridden by setting the path option.
    • This will disable automatic env file resolution.
  • basePath (string)

    • The problem with setting the path option is that you lose environment resolution on the file names.
    • If you don't need environment resolution, the path option is just fine.
  • dotenvParser (string)

    • Path to a custom dotenv parser, relative to the project root (same level as serverless.yml).
    • Parameters passed into the function: { dotenv, paths }.
      • dotenv: dotenv library provided for you or you can bring your own
      • paths: all the dotenv files discovered by the plugin, ordered by precedence (see Automatic ENV File Resolution above for details)
    • This function must return a single object, where each key/value pair represents the env var name and value.
    • By default, this uses the built-in parser, which calls dotenv followed by dotenv-expand for each file.
  • include (list or '*') (default: '*')

    • All env vars found in your file will be injected into your lambda functions.
    • If you do not want all of them to be injected into your lambda functions, you can specify the ones you want with the include option.
    • If set to '*', all env vars in all dotenv files will be injected.
    • If set to an empty list ([]), no env vars will be injected.
    • This option must be set to [] if provider.environment is not a literal string (see FAQ for details).
  • exclude (list)

    • If you do not want all of them to be injected into your lambda functions, you can specify the ones you do not want with the exclude option.
    • Note, this is only available if the include option has not been set.
  • logging: true|false

    • Supresses all logging done by this plugin if no errors are encountered.
  • required

    • env: (list)
      • A set of env var that must be set either in the Serverless environment or via a dotenv file.
      • Throws an error if a required env var is not found.
      • By default, no env vars are required.
    • file: true|false (default false)
      • By default, this plugin will exit gracefully and allow Serverless to continue even if it couldn't find a .env file to use.
      • Set this to true to cause Serverless to halt if it could not find a .env file to use.
  • v4BreakingChanges: true|false (default false)

    • Set this to true to introduce v3.x.x => v4.x.x breaking changes now
  • variableExpansion: true|false (default true)

    • By default, variables can reference other variables
      • E.g. INNER_ENV=innerenv, OUTER_ENV=hi-$INNER_ENV, would resolve to INNER_ENV=innerenv, OUTER_ENV=hi-innerenv
    • Setting this to false will disable this feature
      • E.g. INNER_ENV=innerenv, OUTER_ENV=hi-$INNER_ENV, would resolve to INNER_ENV=innerenv, OUTER_ENV=hi-$INNER_ENV

Example dotenvParser file:

// You can bring your own or use the one provided by the plugin
const dotenv = require('dotenv')
const dotenvExpand = require('dotenv-expand')

module.exports = function({ dotenv, paths }) {
  const envVarsArray = [...paths]
    .reverse()
    .map(path => {
      const parsed = dotenv.config({ path })
      return dotenvExpand(parsed).parsed
    })

  return envVarsArray.reduce((acc, curr) => ({ ...acc, ...curr }), {})
}

Examples

You can find example usage in the examples folder.

Changelog

The changelog is available in the CHANGELOG.md file in the package or on GitHub.

FAQ

This plugin loads the dotenv environment variables inside the plugin constructor. Aside from legacy reasons, this also means all your dotenv environment variables are available to the other plugins being loaded.

However, Serverless variables are not resolved in the constructor:

Variable references in the serverless instance are not resolved before a Plugin's constructor is called, so if you need these, make sure to wait to access those from your hooks. ~https://www.serverless.com/framework/docs/providers/aws/guide/plugins/#plugins/

This is important for several FAQ items below.

How has changes to the Serverless Framework affected when environment variables are loaded?

serverless>=2.26.0

serverless/serverless#8987 changed the order of when plugins are initialized in relationship to variable resolution as part of a larger initiative outlined in serverless/serverless#8364. Because of this, any env var references inside JavaScript files will now get evaluated too early in the process.

serverless>=3.0.0

env variables will get resolved before this plugin is initialized. This means env variables inside serverless.yml can no longer rely on this plugin to load them from dotenv files. See serverless/serverless#8364 for more details on the changes made to the Serverless Framework variables engine.

The Serverless Framework has basic dotenv support built-in. For support with more complicated workflows with dotenv, see serverless-dotenv-example for details.

You can continue to use this plugin to automatically load environment variables into all your functions using dotenv.

How has changes to the Serverless Framework affected configuration options?

See deprecation code UNSUPPORTED_CLI_OPTIONS for more details. This was introduced in serverless/serverless#9171.

serverless>=2.32.0

Using the --env CLI option will now result in the following warning:

Detected unrecognized CLI options: "--env".
Starting with the next major, Serverless Framework will report them with a thrown error
More Info: https://www.serverless.com/framework/docs/deprecations/#UNSUPPORTED_CLI_OPTIONS

serverless>=3.0.0

Using the --env CLI option will now result in the following error:

Error:
Detected unrecognized CLI options: "--env".

Why do env vars already defined by the system take higher precedence?

The Serverless Framework has basic dotenv support built-in. If you are loading variables from .env at the project root, it is possible the Serverless Framework preloads that env var before this plugin does.

As well, because of the variables engine changed in serverless>=2.26.0 (see above), env variables can also be resolved before this plugin runs, which means Serverless could take the values already defined in the system before the plugin loads env vars via dotenv.

Why doesn't the basePath or path options support Serverless variables?

Because Serverless variables have not been interpolated when this plugin runs, basePath and path will always be treated like literal strings (e.g. ${opt:stage} would be presented to the plugin, not the passed in via --stage). The suggested pattern is to store all your dotenv files in one folder, and rely on NODE_ENV, --env, or --stage to resolve to the right file.

There are no plans to support anything other than literal strings at this time, although you are free to discuss this in #52.

Why doesn't this plugin work when provider.environment references another file?

Upgrade to serverless>=2.26.0. The new variables engine introduced in the Serverless Framework in v2.26.0 now resolves file variables first before loading initializing any plugins.

Before v2.26.0, Serverless variables do not get interpolated before this plugin gets initialized, causing provider.environment to be presented to this plugin uninterpolated (e.g. ${file(./serverless-env.yml):environment}). Because of this, the plugin tries to append items to a string instead of a list.

To work around this, you can set the include option to [] to avoid adding any environment variables to provider.environment. However, this means you will have to wire up the environment variables yourself by referencing every single one you need. E.g.

provider:
  environment:
    - DDB_TABLE: ${env:DDB_TABLE}

More details are available at #38.

Contributing

Because of the highly dependent nature of this plugin (i.e. thousands of developers depend on this to deploy their apps to production) I cannot introduce changes that are backwards incompatible. Any feature requests must first consider this as a blocker. If submitting a PR ensure that the change is developer opt-in only meaning it must guarantee that it will not affect existing workflows, it's only available with an opt-in setting. I appreciate your patience on this. Thanks.

serverless-dotenv-plugin's People

Contributors

colynb avatar dependabot[bot] avatar engoyan avatar github-actions[bot] avatar jakechampion avatar mbfisher avatar medikoo avatar mnapoli avatar monkeywithacupcake avatar mrlannigan avatar neverendingqs avatar neverendingqs-bot[bot] avatar pgrzesik avatar sebr avatar thibaultdalban avatar todda00 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

serverless-dotenv-plugin's Issues

[Feature request] Exclude stages

Hi there,

Thanks for this awesome plugin.

I am in a situation where I'd like to IGNORE completely .env files from some environments.

My use case is the following:
I am using .env file only in local, when using the offline plugin.
On "real", deployed environments, env vars are loaded via middy through the ssm middleware (see here).

I am not using ssm in local (offline) mode for many reasons, like:

  • network might not be available
  • each dev might need/want a different configuration
  • avoids unnecessary calls to ssm API

So, when offline, I am using this plugin to load them directly in process.env, and it works great.

This means that I do not want .env files to be loaded/used in stages other than local.

So far, I am working this around by having a .env.local file with my custom variables, and an empty default .env file for the rest.

When in local, I just do
sls offline start -s local --env local.

For the other stages, the empty .env file will just be used and it will just do nothing.

My workaround works.
However, I was wondering it it would make sense to add a new stages option in this plugin to select in which stages you want to load the .env file or not.

A bit like the include one, but per stage instead of per variable.

So, im my use case, I could do:

custom:
  dotenv:
    stages:
      - local

I am sure that others will also find this useful in some other use cases.
For example, one might not want to deploy to prod using a wrong .env file by mistake. One could easily type the wrong ---env or NODE_ENV values.
Excluding prod from the "allowed" stages might then be useful.

WDYT?

BTW, this is inspired by https://github.com/99xt/serverless-dynamodb-local that has this option

${env:MYVAR} not working in serverless.yml

When I run in offline mode (serverless-offline) I'm unable to access the loaded env variables in my serverless.yml. For example in the config below, the ${env:STAGE} always rolls over to the default.

# serverless.yml
service: serverless-framework-starter

plugins:
  - serverless-dotenv-plugin
  - serverless-webpack
  - serverless-offline #serverless-offline needs to be last in the list

custom:
  webpack:
    webpackConfig: 'webpack.config.js'
    includeModules: true
    packager: 'npm'
  serverless-offline:
    port: 4000
  dotenv:
    path: "./.env.${opt:NODE_ENV, 'development'}"

provider:
  name: aws
  runtime: nodejs8.10
  stage: ${env:STAGE, 'dev'}
  region: ${env:REGION, 'us-east-1'}
  versionFunctions: false
  iamRoleStatements:
  -  Effect: "Allow"
     Action:
       - "s3:*"
     Resource: "*"

functions:
  test-func:
    handler: src/test-func/handler.default
    name: ${self:provider.stage}-${self:service}-upload
    memorySize: 128
    events:
      - http:
          path: hello
          method: get
          cors: true

The test handler has no trouble accessing SOMEVAL and it uses the proper value if I change the NODE_ENV at runtime.

// handler.js
const hello = (event, context, callback) => {
  const response = {
    statusCode: 200,
    body: JSON.stringify({
      message: `Go Serverless v1.0! Your function executed successfully! ENV: ${process.env.SOMEVAL}`,
      input: event,
    }),
  };

  callback(null, response);

  // Use this code if you don't use the http event with the LAMBDA-PROXY integration
  // callback(null, { message: 'Go Serverless v1.0! Your function executed successfully!', event });
};

export default hello;

It seems like a timing issue. It seems like the serverless.yml is processed before the serverless-dotenv-plugin is able to load the environment variables into scope. Any idea how I can prove this or whether this is the right concept?

Azure support?

Hello!
I'm trying to migrate from AWS to Azure cloud.
DotEnv plugin is amazing, but I cannot figure it out if I can use it or not :(

Anyone can help?
Thank you very much!

Google / GCP Support?

Does this work for GCP? I am using it for AWS Lambdas and it works, but just wondering if it works for other platforms like Google or Azure.

I saw another issue #40 that Azure might not be supported yet.

Cannot create property error

Keep getting this error
Screen Shot 2020-04-02 at 18 52 14
My custom section looks like

custom:
  globals: ${file(../../serverless.globals.yml)}

with serverless.globals.yml also referring to env variables I set in .env (STAGE being one of them)
Serverless successfully deploys the service but not sure how to get rid of this error

Does this support stages?

I have env specific var files. I.e. .env.dev, .env.prod. I'd like to use the stage to determine which file to load..

Safe to use in production

Hey,

Great plugin, easy to use!

I'm just wondering if this is secure to use for production? And if so, what makes it safe to use for production?

Cheers!

Multiple env files

How do I import both a common env file (without the env suffix), and a env file, e.g. this doesn't seem to work:

custom:
  dotenv:
    path: ../common.env:../site.env.dev

[aws codebuild] dotenv is not working

I am using serverless and serverless dotenv plugin.

And it is working properly.

But, our team move to aws codepipeline and codebuild for ci/cd.

Our project's ignore .env.* files to push github.

So, using codebuild envrionment variales.

But, it is not working.

I run this command in codebuild

- printenv

And injected environment variables showing.

But node.js process.env has not.

How to inject aws codebuild environment variables to node.js process.env using serverless-dotenv-plugin?

I tried below comman in codebuild

- printenv > .env.production

But, it is not working.

build size is just 4.98MB but, lambda upload size too large error occured.

how to do...?

my setting info

node.js : 10.15
aws buildspec : 0.2
serverless framework with serverless-webpack-plugin and serverless-dotenv-plugin ( with node dotenv npm )

And push my .env files to github, it is working properly.

So, I think that serverless-dotenv-plugin is not using aws codebuild env variables

Thank you.

Support for local env values or multiple paths

create-react-app has an awesome environment variables resolution pattern:
https://create-react-app.dev/docs/adding-custom-environment-variables/#what-other-env-files-can-be-used
It allows for users to define .env.development (tracked by git) and .env.development.local (not committed to the repo), .env which works on all envs, etc.

Another issue proposed to allow multiple paths, but in another context: #29.

This way, you could perhaps configure the plugin like this (given path supports variables: #52):

custom:
  dotenv:
    path: 
        - .env
        - .env.${self:stage}
        - .env.${self:stage}.local

The plugin would load each path sequentially, overriding envs as it goes.

Alternatively, the plugin would do these resolutions automatically.

This is the implementation on create-react-app. It takes into account several framework-specific things, but the main part, which applies here, is this: https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/config/env.js#L26-L49

EDIT

Apparently, this behaviour was taken from Rails:
https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use

I made the change on a fork of mine

Question: Interpolation inside of .env* files?

Hey,

first of all: Thank you for your work on this plugin. We just started implementing a serverless api and need env-var support. Unfortunately, we need access to Cloudformation-Outputs inside of the env vars, e.g. for a Subnet-ID.
What we did so far is more of a workaround by specifying the env vars multiple times:

custom:
  stage: "${opt:stage,'dev'}",
  env:
    dev:
      dbHost: "127.0.01"
    prod: 
      dbHost: "${cf:Stack.dbHost}"

...
functions:
  test:
  ..
    environment: 
      dbHost: "self:custom.env.${opt.stage}.dbHost

(no guarantees on correct indentation ๐Ÿ˜„ )
We would love to manage all of the env variables in their dedicated files and just have a ${env:dbHost} in the functions section without the ugly repetition in custom . Is there a way to achieve this?

Thanks in advance!

Create CHANGELOG.md file in project root

Overview

As a user, I would like to see a CHANGELOG.md file in the project root that is up to date with the current release.

I see there is a changelog on your private blog, but it is missing the latest version bump (3.1.0), and it would be nicer for the library if that lived inside the project repo.

Examples

Here are a couple of changelog file examples, I don't think an automatic changelog generator is necessary, but the format is common and easy to read.

https://github.com/github-changelog-generator/Github-Changelog-Generator/blob/master/CHANGELOG.md
https://github.com/olivierlacan/keep-a-changelog/blob/master/CHANGELOG.md

Let users define dotenv plugins?

I am porting a project to serverless, where it has a number of dotenv plugins already in place, particularly dotenv-parse-variables we use there.

I see that you already added dotenv-expand plugin in the source code, do you think it's a good idea to expose an array in serverless.yml:custom.dotenv.plugins for users to define their own plugins?

Native support for .env in Serverless Framework

@colynb great thanks for this plugin!

We're currently investigating a possibility of supporting .env file natively in a Framework.

Main reason is that ideally env vars from .env should be loaded at very begin of a process, and resolution via plugin is delayed simply by its nature. So taking into account dotenv popularity I believe it's a good call to make it a first class citizen in the Framework (it's also already supported in Serverless Components)

Also we simply plan to support it it as convenient env vars transport into process.env and nothing more (no automatic leak into lambdas etc.)

We will value your feedback at serverless/serverless#7907

plugin ignores custom definitions when places in an external file

My serverless.yml references an external file:

custom: ${file(../../serverless.common.yml):custom}

Placing settings inside serverless.common.yml:

custom:
  dotenv:
    path: ../../.env

serverless.dotenv-plugin ignores these settings.
When debugging plugin code, row 13 leaves this.config undefined:

    this.config =
      this.serverless.service.custom && this.serverless.service.custom['dotenv']

because this.serverless.service.custom equals: "${file(../../serverless.common.yml):custom}"

URLs ENVs output as [object Object] when using serverless-offline

When I set a URL in my .env.developement file and run using serverless-offline, I get the value as [object Object]

e.g.

ITEMS_TO_PARSE_QUEUE=https://sqs.eu-central-1.amazonaws.com/1234/items-to-parse

console.log(process.env.ITEMS_TO_PARSE_QUEUE); // returns [object Object]

Reference to env vars sitting outside main config yml causes error

Error:

 Serverless Plugin Error --------------------------------------

  Cannot create property 'DYANMODB_TABLE' on string '${file(./serverless-env.yml):environment}'

configs:

serverless.yml

service: my-service

plugins:
  - serverless-dotenv-plugin

provider:
  name: aws
  runtime: nodejs8.10
  environment: ${file(./serverless-env.yml):environment}

serverless-env.yml

environment:
  SLS_AWS_STAGE: ${env:DYANMODB_TABLE, 'xxvvv'}

No errors when moving environment to outside the provider. Verified that it's working perfectly when it's located outside provider.

Location of changelog

Hi, I was updating from a previous version to the latest version of this plugin. Is there a link where I can see the changelogs?
Thanks

Not setting ENV vars on Lambda, v1.1.2

This plugin would read the env file but the env variables would not be set on the AWS lambda function. Maybe it was conflicting with other plugins.
I managed to fix it by adding the hook:
"before:package:initialize": this.loadEnv.bind(this)
to this.hooks in the constructor in index.js.

Maybe this would help anyone.
I'm not convinced this is an universal solution as to create a pull request.

Read issues when value has '$' character

I have observed an issue while reading a value that contains '$' character.
While reading the value using 'process.env', the $ character, as well as the next few characters, are missing.

As an example, consider the below line in .env.local file:

TEST_1=123$456!@#%^&*()

While reading I see that
process.env.TEST_1 = 123!@#%^&*() // A total of four characters are missing from the original value which are '$456'.

Unable to get .env with a dynamic path

I am trying to set dynamic .env files based on stage. The serverless is unable to find those .env files.

Here is my serverless.yml file:

custom:
   dotenv:
      path: environment/.env.${self:provider.stage}
provider:
  stage: ${opt:stage, 'dev'}

If the path is static as below, it is working just fine

custom:
       dotenv:
           path: environment/.env.dev

Expected behavior:
DOTENV should resolve path to environment/.env.dev

Current behavior:
Unable to resolve path

"app" value in Serverless.yml not working

Hello,

I tried using Serverless enterprise with the following configuration;
service: ${env:APP_NAME}
...
app: ${env:SLS_APP_NAME}

However, it seems like ${env:SLS_APP_NAME} isn't being replaced by its value. While I replace it manually, everything works fine.
I can confirm it's not due to the variable not being in the .env, or the wrong environment.

Is this a known bug?

Thanks,
Will

Does this work for `serverless offline`

I'm trying to use this for testing/offline/deployment. Does this work if I run serverless in offline mode? If I remove the .env file and run serverless offline start it doesn't throw an error. That leads me to believe it isn't being run in offline mode.

How do you set the options?

README says you can set some options like path, but i don't get how do you add these to the serverless.yaml file

1.2.0 breaks serverless interpolation

Hi there,

I love your plugin and I use it for my current pet project. I guess something has broken in the last version. This works in 1.1.5

custom:
  dotenv:
    path: .${self:provider.stage}.env

It will load stage specific files like .dev.env.
In 1.2.0 it can't find the file anymore. envPath is just .${self:provider.stage}.env. I think this related to change when the plugin loads the env file.

Thanks!

The --stage parameter ignored when looking for the right .env file

I'm running the serverless script with the next command line:
client deploy --stage prod --region eu-west-1 --aws-profile MyProfile

As you see I'm specifying the --stage parameter, which according to this documentation should use the .env.prod file.

But I'm getting this message:
Serverless: DOTENV: Could not find .env file.

All .env files are in sub-folder envs and here is my serverless config:

service: my-sevice-${opt:stage, self:provider.stage}

frameworkVersion: ">=1.1.0 <2.0.0"

plugins:
  - serverless-finch
  - serverless-dotenv-plugin

custom:
  dotenv:
    basePath: ./envs/
    include:
      - MY_VARIABLE

  ...

provider:
  name: aws
  runtime: nodejs12.x
  stage: ${opt:stage, 'develop'}

[QUESTION] Serverless Hooks

Hi,
What's the reason behind the hooks on serverless stages?
If I need the env variables in other hooks rather than the hardcoded in the plugin class, what's the point to have hooks hardcoded?

Why not just to load the env variables regardless of the current serverless stage?

Thanks in advance,

Just to say thanks

Just want to say, great work with this. Was thinking I would have to implement it myself, till I stumbled on this. I'm also willing to volunteer as a maintainer if you ever need help.

Also, what do you think of getting this into the core framework? It's a terribly useful feature because for anyone using version control, managing secrets is hell (copy them out from your serverless.yml before you commit).

Using serverless-dotenv-plugin increases lambda package size

Hey guys, sorry to bother you, I really enjoyed how easy it is to use the plugin. Nevertheless, I'm having issues trying to deploy bc my package's final size is pretty big, over 270MB. That being said, I don't know if it has anything to do with the plugin, but when I remove it, it goes down to 405KB ๐Ÿ˜ฌ

./node_modules/.bin/sls --version
Framework Core: 2.18.0 (local)
Plugin: 4.4.2
SDK: 2.3.2
Components: 3.4.6

Fragment of my serverless.yml (although there's not much to look there)

service: xxxxx

frameworkVersion: ^2.16.1

plugins:
  - serverless-dotenv-plugin

custom:
  cors:
    allowCredentials: false
    origin: '*'
    headers:
      - Authorization
      - Content-Type
      - X-Amz-Date
      - X-Api-Key
      - X-Amz-Security-Token
      - X-Amz-User-Agent

package:
  excludeDevDependencies: true
  exclude:
    - .vscode
    - docker
    - .git/**

Let me know if it's not an issue with the plugin so I can file another issue. Let me know if I can help with anything

Fail silently

Locally I have .dotenv files, but the CI/CD pipelines use real environment variables. As a result each build ends up with this in the log

Serverless: DOTENV: Loading environment variables:

 Serverless Plugin Error --------------------------------------

  [serverless-dotenv-plugin] Could not find .env file.

It'd be nice if an option could be provided in serverless.yml to fail silently

[FEATURE REQUEST] additional option - exclude

Hi here,

Thanks for creating this awesome plugin mate! Helped me a lot :)

I would like to know your thoughts regarding adding an additional option - exclude
It's helpful in my case since i just want to blacklist a list of ENVs that I don't want to use & push

Missing custom property in serverless config causes an error

SLS_DEBUG=* sls invoke local -f handler -p event.js

Results in no .env loaded and the following error

Serverless: DOTENV: Loading environment variables:
 Serverless Plugin Error --------------------------------------

  Cannot read property 'dotenv' of undefined

Appears to be caused by

var config = this.serverless.service.custom['dotenv'];

Because I don't have a custom section in my serverless.yml.

Temporary workaround

custom:
  dotenv:
    see: https://github.com/infrontlabs/serverless-dotenv-plugin/issues/5

Name resolution stop working when I set `path` and `basePath` options

I configured this plugin in serverless.yml as below:

custom:
  dotenv:
      basePath: config
      path: config/.env

I have some env files under config directory:

config/.env
config/.env.joey

when I deploy with a stage name joey, e.g. sls deploy --stage joey, it still loads file config.env. It doesn't look at config.env.joey. The output is always:

Serverless: DOTENV: Loading environment variables from config/.env:

If I remove the option basePath and path from serverless.yml file and put these env files in the default location which is ./. Everything works fine. Could you support automatic name resolution with customised path?

possible bug - environment variable value being cut

I have an ENV variable, say RANDOM_HASH in my .env file

.env

RANDOM_HASH="XXXXX#XXXXX%9^XX$4$FYNHtpPs6uc"

and on
serverless.yml

custom:
  dotenv:
    include:
      - RANDOM_HASH

when i deploy it, what reaches my lambda function only is XXXXX#XXXXX%9^XX
Somehow, it has been cut in the first $

same thing is found on the cloudformation-template-update-stack.json file

        "Environment": {
          "Variables": {
            "RANDOM_HASH": "XXXXX#XXXXX%9^XX"
          }
        }

so i suspect that the library somehow accidentally split the content.
Do you have some work around in mind, so that I can upload the same env variable value?

Thanks in advance!

How to *NOT* load into Lambda?

I further suffix env vars I load from files in serverless.yaml, so I don't want the original vars loaded into Lambda. Is there an option to turn that off?

Environment Vars Don't Update In AWS Console

Hi, I am using this plugin to set my environment variables. It works with "serverless offline", but when I deploy none of the environment variables are updated. why is this? thanks

Try automatic resolution based on path and not load from the path

So I have this monorepo setup where I want to have my .env.development and .env.production at the root level and reference the required variables in my service folders.
Right now the path variable tries to load it directly from the file, without trying to find the file.

The issue with this approach is that if I hardcode what is my .env right now. I might have to change the path name in each service folder to production and then deploy. Which is cumbersome and feels wrong.

What I would like an option as readFrom and given a path and the whole thing will run on that path instead of the current repo.

What do you guys think around this? Anybody faced same issue? I Might want to put in a PR on this but need suggestions from collaborators, also is there anyway we can currently do this that I might be missing?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.