Javascript is required
5 min read

How to Use Environment Variables to Store Secrets in AWS Amplify Backend

How to Use Environment Variables to Store Secrets in AWS Amplify Backend Image

The twelve-factor app is a known methodology for building software-as-a-service apps. One factor describes that an application's configuration should be stored in the environment and not in the code to enforce a strict separation of config from code.

In this article, I want to demonstrate how you can add sensitive and insensitive configuration data to an AWS Amplify backend using environment variables and AWS Secrets Manager.

Types of configuration

There exist many types of configuration data, for example:

  • timeouts
  • connection strings
  • external API configurations like URLs and endpoints
  • caching
  • hosting configuration for URL, port, or schema
  • file system paths
  • framework configuration
  • libraries configuration
  • business logic parameters
  • and many more

Apart from the type, configuration data can also be categorized as sensitive or insensitive.

Sensitive vs Insensitive

Sensitive configuration data is anything that can be potentially exploited by a third party and therefore must be protected from unauthorized access. Examples of such sensitive data are API keys, usernames, passwords, emails, etc. This data should not be part of your version control. Insensitive configuration data is for example a timeout string for a backend endpoint that can be safely added to the version control.

Init Amplify


You need an AWS account and the Amplify CLI installed and configured to be able to follow the following steps. Check out the official docs to set up the prerequisites.

Let's start by creating a new Amplify project:

1mkdir amplify-env-config-demo
2cd amplify-env-config-demo
4 amplify init
5? Enter a name for the project amplifyenvconfigdemo
6? Initialize the project with the above configuration? Yes
7? Select the authentication method you want to use: AWS profile
8? Please choose the profile you want to use default

Next, we can add an API which we will use to add some environment configuration.

1 amplify add api
2? Please select from one of the below mentioned services: REST
3? Provide a friendly name for your resource to be used as a label for this category in the project: amplifyenvconfigdemoapi
4? Provide a path (e.g., /book/{isbn}): /handle
5? Choose a Lambda source Create a new Lambda function
6? Provide an AWS Lambda function name: amplifyenvconfigdemofunction
7? Choose the runtime that you want to use: NodeJS
8? Choose the function template that you want to use: Hello World
9? Do you want to configure advanced settings? No
10? Do you want to edit the local lambda function now? No
11? Restrict API access No
12? Do you want to add another path? No

We create a simple Node.js lambda function based on the "Hello World" Amplify template. It will provide a REST API with an endpoint at the path /handle.

Amplify CLI generated the "Hello World" function code at amplify/backend/function/amplifyenvconfigdemofunction/src/index.js:

1exports.handler = async (event) => {
2  const response = {
3    statusCode: 200,
4    //  Uncomment below to enable CORS requests
5    //  headers: {
6    //      "Access-Control-Allow-Origin": "*",
7    //      "Access-Control-Allow-Headers": "*"
8    //  },
9    body: JSON.stringify('Hello from Lambda!'),
10  }
11  return response

Add insensitive configuration data

As we now have a running API, we can add some insensitive configuration data as environment variables to our Amplify backend.

Therefore, we need to modify the amplify/backend/function/amplifyenvconfigdemofunction/amplifyenvconfigdemofunction-cloudformation-template.json file. It includes a Parameters object where we can add a new environment variable. In our case we want to add a string variable that can be accessed with the key MyEnvVariableKey and has the value my-environment-variable:

2  "AWSTemplateFormatVersion": "2010-09-09",
3  "Description": "Lambda Function resource stack creation using Amplify CLI",
4  "Parameters" : {
5    ...
6    "env": {
7      "Type": "String"
8    },
9    "s3Key": {
10      "Type": "String"
11    },
12    "MyEnvVariableKey" : {
13      "Type" : "String",
14      "Default" : "my-environment-variable"
15    }
16  },
17  ...

We also need to modify the Resources > Environment > Variables object in this file to be able to map our new environment key to a variable that is attached to the global process.env variable and is injected by the Node.js runtime:

2  "Resources": {
3    "Environment": {
4      "Variables": {
5        "ENV": {
6          "Ref": "env"
7        },
8        "REGION": {
9          "Ref": "AWS::Region"
10        },
11        "MY_ENV_VAR": {
12          "Ref": "MyEnvVariableKey"
13        }
14      }
15    }
16  }

Finally, we need to run amplify push to build all of our local backend resources and provision them in the cloud.

Now we can access this variable in our lambda function by accessing the global process.env variable:

1exports.handler = async (event) => {
2  console.log('MY_ENV_VAR', process.env.MY_ENV_VAR)
4  const response = {
5    statusCode: 200,
6    body: JSON.stringify('Hello from Lambda!'),
7  }
8  return response

Add sensitive data using AWS Secrets Manager

AWS provides the AWS Secrets Manager that helps to "protect secrets needed to access your applications, services, and IT resources". We will use this service to be able to access sensitive data from our backend.

First, we need to click on "Store a new secret" to create a new secret:

Store new secret

Next, we click "Other type of secret" and enter key and value of our secret in the corresponding "Secret key/value" inputs:

Secret type

It is possible to add multiple key/value pairs to a secret. A new pair can be added by clicking the "+ Add row" button.

In the next screen we need to add a name and some other optional information to our secret:

Secret name and description

Let's finish the wizard by skipping all the following screens by clicking the "Next" button.

Now we can open the secret and inspect its values inside the AWS Secrets Manager:

Secret details

We need to copy the "Secret ARN" value as we need to add a new configuration object in our Cloudformation configuration file amplifyenvconfigdemofunction-cloudformation-template.json:

1"lambdaexecutionpolicy": {
2  "DependsOn": ["LambdaExecutionRole"],
3  "Type": "AWS::IAM::Policy",
4  "Properties": {
5  "PolicyName": "lambda-execution-