Environment variables

Environment variables are the perfect solution to configure the application (as recommended in the 12 factor guide).

Definition

Environment variables can be defined in serverless.yml.

To define an environment variable that will be available in all functions declare it in the provider section:

provider:
    # ...
    environment:
        MY_VARIABLE: 'my value'

To define an environment variable that will be available in a specific function declare it inside the function's properties:

functions:
    foo:
        # ...
        environment:
            MY_VARIABLE: 'my value'

Do not store secret values in serverless.yml directly. Check out the next section to handle secrets.

Secrets

Secrets (API tokens, database passwords, etc.) should not be defined in serverless.yml and committed into your git repository.

Instead you can use the SSM parameter store, a free service provided by AWS.

To create a parameter you can either do it manually in the SSM parameter store console or use the following command:

aws ssm put-parameter --region us-east-1 --name '/my-app/my-parameter' --type String --value 'mysecretvalue'

It is recommended to prefix the parameter name with your application name, for example: /my-app/my-parameter.

To import the SSM parameter into an environment variable you can use the ${ssm:<parameter>} syntax:

provider:
    # ...
    environment:
        MY_PARAMETER: ${ssm:/my-app/my-parameter}

An alternative: AWS Secrets Manager

As an alternative you can also store secrets in AWS Secrets Manager. This solution, while very similar to SSM, will provide:

  • better permission management using IAM
  • JSON values, allowing to store multiple values in one parameter

However Secrets Manager is not free: pricing details.

Local development

When developing locally using serverless invoke local you can override environment variables via the --env option:

serverless invoke local --docker -f <Function> --env VAR1=val1 --env VAR2=val2

Learn more

While this page mentions environment variables, serverless.yml allows other types of variables to be used.

Read the serverless.yml variables documentation to learn more.