How to save up on AWS Parameter Store with serverless framework



The Drawback:

It’s a unhealthy observe and even a safety threat to make use of hard-coded values inside our code that reference an API Key or a Database Password. Alternatively, we will have values that may change over time due to a enterprise determination or an unexpected scenario; this can imply that we’ve got to alter our code each time a worth must be modified. For this, we will use the AWS Methods Supervisor service known as Parameter Retailer.

Parameter Store is a functionality of AWS Methods Supervisor that gives safe, hierarchical storage for configuration information administration and secrets and techniques administration. We are able to retailer information resembling passwords, database strings, Amazon Machine Picture (AMI) IDs, and license codes as parameter values. We are able to retailer values as plain textual content or encrypted information.

Nonetheless, what occurs when we’ve got to make use of a number of variables? It’s troublesome to take care of them, however the issue doubles with a number of growth environments. We are able to simply attain the laborious cap restrict of 10,000 customary parameters per account and area.



How can we remedy this?

We are able to save a number of parameter shops; if we begin writing them in JSON format, we will have them organized in a transparent and arranged method.

Allow us to begin making a Parameter Retailer with our JSON values. I’ll use my first and final title as values for this instance.

/dev/myapp/INFO >> {"firstName":"David","lastName":"Llerena"}
Enter fullscreen mode

Exit fullscreen mode

Create a Typescript serverless Lambda Challenge with serverless framework. Let’s add the next dependencies:

//bundle.json
{
  "title": "myapp",
  "model": "1.0.0",
  "description": "",
  "primary": "index.js",
  "scripts": {
    "check": "echo "Error: no check specified" && exit 1"
  },
  "dependencies": {
    "aws-sdk": "2.952.0",
    "@sorts/aws-lambda": "^8.10.95",
    "serverless": "^3.15.2",
    "serverless-plugin-typescript": "^2.1.2",
    "typescript": "^4.6.3"
  },
  "creator": "",
  "license": "ISC"
}
Enter fullscreen mode

Exit fullscreen mode

Now let’s create some javascript code in a file named helperScript.js, Create a operate that may name SSM service and browse a Parameter retailer which we want to parse and browse every worth of the JSON values. ResolveConfigurationProperty assertion will reference the stage and title of our service, declared in our serverless.yml file.

//helperScript.js
const SSM = require("aws-sdk/purchasers/ssm");

module.exports.getParameters = async ({ resolveConfigurationProperty }) => {
  const prefix = await resolveConfigurationProperty(["custom", "prefix"]);
  const area = await resolveConfigurationProperty(["provider", "region"]);
  const ssm = new SSM({ area });
  const coverage = await ssm
    .getParameter({
      Title: prefix + "/INFO",
      WithDecryption: true,
    })
    .promise();
  const res = JSON.parse(coverage.Parameter.Worth);
  return {
    firstName: res.firstName,
    lastName: res.lastName

  };
};
Enter fullscreen mode

Exit fullscreen mode

In our serverles.yml file, we are going to reference this helperScript.js to name the variables utilized in our code beneath the surroundings assertion. Give the lambda the required permissions to entry the SSM service. It is strongly recommended solely to provide entry to the sources we’re utilizing.

If we’re utilizing a serverless model minor to model 3, we’ve got so as to add this assertion variablesResolutionMode: 20210326 beneath service declaration

#serverless.yml
service: myapp

plugins:
  - serverless-plugin-typescript

supplier:
  title: aws
  runtime: nodejs16.x
  stage: dev
  area: us-east-1
  surroundings:
    FIRST_NAME: ${file(./helperScript.js):getParameters.firstName}
    LAST_NAME: ${file(./helperScript.js):getParameters.lastName} 
  iamRoleStatements:
    - Impact: "Enable"
      Motion:
        - ssm:GetParameter
        - ssm:GetParameters
        - ssm:GetParametersByPath
      Useful resource: "*"
customized:
  prefix: /${self:supplier.stage}/${self:service}
capabilities:
  good day:
    handler: handler.good day
Enter fullscreen mode

Exit fullscreen mode

Lastly, let’s use this Parameter Retailer in our lambda code.

//handler.ts
import { Handler } from 'aws-lambda';

export const good day: Handler = (occasion: any) => {
  const response = {
    statusCode: 200,
    physique: JSON.stringify(
      {
        message: 'My First title is '+`${course of.env.FIRST_NAME}`+' and my final title is '+`${course of.env.LAST_NAME}`
      },
      null,
      2
    ),
  };

  return new Promise((resolve) => {
    resolve(response)
  })
}
Enter fullscreen mode

Exit fullscreen mode

And that is it!, if we execute our lambda it ought to appear to be this:
Lambda Execution

This can absolutely assist us save up some Parameter Shops and maintain them neat and clear. Nonetheless, we must always think about the scale that these variables might get. We’d think about using Advanced Parameters.

Reference: Serverless Framework Variables

Add a Comment

Your email address will not be published. Required fields are marked *