Using JSON as String for Environment Variables the Serverless Framework

Using JSON as String for Environment Variables  the Serverless Framework

Environment variables are a crucial component of AWS Lambda that allows you to pass configuration data to your functions.

In this blog post, we will explore how to use environment variables for AWS Lambda using the Serverless Framework.

Step 1: Create a new Serverless service First, we need to create a new Serverless service by running the following command in your terminal:

$ serverless create --template aws-nodejs --path my-service

This command will create a new Serverless service in the my-service directory with a basic AWS Node.js template.

Step 2: Define your environment variables Next, we can define our environment variables by adding them to the serverless.yml file. Here's an example:

service: my-service

params:
  default:
    REGION: ${opt:region, 'us-east-1'}
    STAGE: ${opt:stage, 'dev'}
    AWS_ACCOUNT_ID: ${aws:accountId}
  dev:
    PLAN_ID1: '{"id":"49605","host":"ccma127.loca.lt","path":"/api/paddle-webhook"}'
  prod:
    PLAN_ID1: '49605'  
provider:
  name: aws
  runtime: nodejs14.x
  environment:
    PLAN_ID1: ${param:PLAN1 }

functions:
  hello:
    handler: handler.hello
    events:
      - http:
          path: /
          method: get

In this example, we are defining an environment variable called MY_ENV_VAR with a value of my-value. You can add as many environment variables as you need, separated by commas.

Step 3: Access the environment variables in your Lambda function Finally, we can access the environment variables in our Lambda function using the process.env object. Here's an example:

exports.hello = async (event) => {
  const myEnvVar = JSON.parse(process.env.PLAN_ID1);
  return {
    statusCode: 200,
    body: `My environment variable value is: ${myEnvVar}`
  };
};

In this example, we are accessing the MY_ENV_VAR environment variable using process.env.PLAN_ID1 and returning its value in the response body.

AWS Lambda Environment

AWS Lambda Environment Variables

Using environment variables for AWS Lambda using the Serverless Framework is a powerful way to pass configuration data to your functions. By following these simple steps, you can use JSON as the string for Lambda functions that are easy to maintain and update over time.

Did you find this article valuable?

Support Dorothi Viki by becoming a sponsor. Any amount is appreciated!