Javascript is required
·
5 min read
·
7118 views

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

Info

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:

bash
1mkdir amplify-env-config-demo
2cd amplify-env-config-demo
3
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.

bash
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
12}

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:

json
1{
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  ...
18}

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:

json
1{
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  }
17}

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)
3
4  const response = {
5    statusCode: 200,
6    body: JSON.stringify('Hello from Lambda!'),
7  }
8  return response
9}

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:

json
1"lambdaexecutionpolicy": {
2  "DependsOn": ["LambdaExecutionRole"],
3  "Type": "AWS::IAM::Policy",
4  "Properties": {
5  "PolicyName": "lambda-execution-policy",
6  "Roles": [{ "Ref": "LambdaExecutionRole" }],
7  "PolicyDocument": {
8    "Version": "2012-10-17",
9    "Statement": [
10        {
11          "Effect": "Allow",
12          "Action": ["secretsmanager:GetSecretValue"],
13          "Resource": {
14            "Fn::Sub": [
15              "arn:aws:secretsmanager:${region}:${account}:secret:key_id",
16              {
17                "region": {
18                  "Ref": "AWS::Region"
19                },
20                "account": {
21                  "Ref": "AWS::AccountId"
22                }
23              }
24            ]
25          }
26        }
27      ]
28    }
29  }
30}

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

Now we need to add some JavaScript code to be able to access the secret inside our Node.js lambda function.

First, we need to add the AWS SDK to amplify/backend/function/amplifyenvconfigdemofunction/src/package.json by running:

bash
npm install aws-sdk

Then we can use the SecretsManager to get our secret values by passing the "Secret name" which we defined in the AWS Secrets Manager:

1const AWS = require('aws-sdk')
2const secretsManager = new AWS.SecretsManager()
3
4exports.handler = async (event) => {
5  console.log('MY_ENV_VAR', process.env.MY_ENV_VAR)
6
7  const secretData = await secretsManager.getSecretValue({ SecretId: 'dev/demoSecret' }).promise()
8  const secretValues = JSON.parse(secretData.SecretString)
9
10  console.log('DEMO_API_KEY', secretValues.DEMO_API_KEY)
11
12  const response = {
13    statusCode: 200,
14    body: JSON.stringify('Hello from Lambda!'),
15  }
16  return response
17}

Conclusion

In this article, I demonstrated how you can add sensitive and insensitive environment configuration to your AWS Amplify backend. You can also watch this video from Nader Dabit if you prefer a visual tutorial.

If you liked this article, follow me on Twitter to get notified about new blog posts and more content from me.

I will never share any of your personal data. You can unsubscribe at any time.

If you found this article helpful.You will love these ones as well.
How I Replaced Revue With a Custom-Built Newsletter Service Using Nuxt 3, Supabase, Serverless, and Amazon SES Image

How I Replaced Revue With a Custom-Built Newsletter Service Using Nuxt 3, Supabase, Serverless, and Amazon SES

The 10 Favorite Features of My Developer Portfolio Website Image

The 10 Favorite Features of My Developer Portfolio Website

How I Built a Twitter Keyword Monitoring Using a Serverless Node.js Function With AWS Amplify Image

How I Built a Twitter Keyword Monitoring Using a Serverless Node.js Function With AWS Amplify

Track Twitter Follower Growth Over Time Using A Serverless Node.js API on AWS Amplify Image

Track Twitter Follower Growth Over Time Using A Serverless Node.js API on AWS Amplify