Zoe Edwards
Zoe Edwards

Reputation: 13667

Setting the env using a .env file in Serverless

Using the Serverless framework, I want to be able to change the AWS region from an envrionment variable.

provider:
  name: aws
  region: ${env:AWS_REGION}

Then, AWS_REGION can be set to eu-west-2.

However, I want to have that set in a .env file:

AWS_REGION=eu-west-2

And then have that .env read by Serverless.

There are many topics about setting variables in the serverless.yml file, and exporting them from that file, but I want to put them into the file.

Upvotes: 3

Views: 5847

Answers (3)

Muhammad Ibrahim
Muhammad Ibrahim

Reputation: 321

use this plugin to write .env with serverless.yaml serverless-export-env. so you just need to overwrite your region inside serverless yaml, and your env will be generated based on whay you've written in serverless.yaml.

Upvotes: 0

Nicolai Lissau
Nicolai Lissau

Reputation: 8302

Serverless now supports .env files without the need for a plugin

  1. Add useDotenv: true to your serverless.yml file. The variable should be at the root level, same as service: ...

  2. Add a .env file at the root of your project and serverless will load the variables.

Example:

// .env
MY_TABLE=A_TABLE_NAME

Upvotes: 7

noetix
noetix

Reputation: 4923

Out of the box serverless doesn't parse .env, that part belongs to you.

I see three options for you:

  1. Use the serverless-dotenv-plugin.

  2. Write a script that exports .env vars to your local environment before you run serverless.

  3. Run serverless in docker-compose which is .env aware -- I use this in combination with Makefile, even in a CI/CD context.

Upvotes: 6

Related Questions