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
  • 12,999
  • 3
  • 24
  • 43
  • 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

3 Answers3

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,773
  • 3
  • 26
  • 47
3

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
Nicolai Lissau
  • 7,298
  • 5
  • 43
  • 57
0

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.