2

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.

Zoe Edwards
  • 11,939
  • 3
  • 19
  • 40
  • Is it feasible for your case to export those `.env` file content to a yaml file. The [docs](https://serverless.com/framework/docs/providers/aws/guide/variables/#reference-variables-in-other-files) support referencing variables from other yaml/json files, but there is no evidence for an .env – vahdet Mar 01 '19 at 14:15
  • Good question @vahdet. The reason for a .env locally is that it’s easier on CI/CD to just use envs. I have thought about a JSON or YAML file, but I would have to build it from envs on the CI/CD. – Zoe Edwards Mar 01 '19 at 14:17

2 Answers2

5

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.

noetix
  • 4,533
  • 2
  • 25
  • 46
2

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
Attaque
  • 5,466
  • 3
  • 32
  • 49