Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get environment variables defined in serverless.yml in tests

I am using the serverless framework for running lambda functions on AWS.

In my serverless.yml there are environment variables that are fetched from SSM.

When I write integration tests for the code, I need the code to have the environment variables and I can't find a good way to do this.

I don't want to duplicate all the variables definitions just for the tests, they are already defined in the serverless.yml. Also, some are secrets and I can't commit them to source conrol, so I would have to also repeat them in the ci environment.

Tried using the serverless-jest-plugin but it is not working and not well maintained.

Ideas I had for solutions:

  1. Make the tests exec sls invoke - this will work but would mean that the code cannot be debugged, I won't know the test coverage, and it will be slow.
  2. Parse the serverless.yml myself and export the env variables - possible but rewriting the logic of pulling the SSM variables just for tests seems wrong.

Any ideas?

like image 367
brafdlog Avatar asked Nov 09 '18 20:11

brafdlog


People also ask

How do I use environment variables in serverless yml?

To reference environment variables, use the ${env:SOME_VAR} syntax in your serverless. yml configuration file. It is valid to use the empty string in place of SOME_VAR .

What are the valid file type to store variables for serverless YAML?

yml file: You can store your variables in serverless. yml if they don't contain sensitive data, and then reference them elsewhere in the file using self:someProperty .

Who set up environment in serverless?

In Serverless the environment is setup by the cloud provider. Many server-like access, such as process, log files, and SSH are unavailable to a Serverless user.


1 Answers

The solution we ended up using is a serverless plugin called serverless-export-env.

After adding this plugin you can run serverless export-env to export all the resolved environment variables to an .env file. This resolves ssm parameters correctly and made integration testing much simpler for us.

BTW, to get the environment variables set from the .env file use the the dotenv npm package.

Credit to grishezz for finding the solution

like image 111
brafdlog Avatar answered Oct 06 '22 17:10

brafdlog