AWS Parameter and Secrets Lambda extension - Node.js example
Tags: lambdaextension, parameterstore, lambda, extension
Published: 2022-11-26 15:18:59

### TLDR;
This blog walks through how to access values stored in AWS Systems Manager Parameter Store via Lambda extension using Node.js code.

### What is Lambda extension:
AWS releases Lambda extensions as Layer to make developers life easier by helping them integrate Lambda with other AWS Services features (like AppConfig, AWS Systems Manager Parameter Store etc.).

### How Lambda extension works:
Lambda lifecycle has 3 phases: init, invoke and shutdown.
_Init phase_ - Combination of Extension INIT, Runtime INIT and Function INIT. Extension setup happens during Extension INIT phase.
_Invoke phase_ - Extension exposes HTTP endpoint that can be called from Lambda function runtime. 
_Shutdown phase_ - Extension runtime shutdown along with Lambda function runtime.

#### Why use AWS Systems Manager Parameter Store: 
To store connection details, credentials or keys etc.

#### How AWS Parameters and Secrets Lambda extension works:
Provides in-memory cache for parameters and secrets. Upon Lambda requesting a parameter, the extension fetches the parameter data from local cache, if available. If data not in cache or stale, the extension fetches parameter value from AWS Systems Manager service. This reduces aws-sdk initialization, API calls, reduces cost and improves application performance.

#### Nodejs example:
```
const http = require('http');

let getParameterValue = function(paramName) {
    const headers = {
        "X-Aws-Parameters-Secrets-Token': process.env.AWS SESSION TOKEN
    }

    let options = {
        host: "localhost',
        port: '2773',
        path: `/systemsmanager/parameters/get?name=${paramName}`,
        method: 'GET',
        headers: headers
    }

    return new Promise((resolve, reject) => {
        const req = http.get(options, (res) => {
            if (res.statusCode < 200 || res.statusCode >= 300) {
                return reject(new Error('statusCode=' + res.statusCode));
            }
            var body = [];
            res.on('data', function(chunk) {
                body.push(chunk);
            });
            res.on('end', function() {
                resolve(Buffer.concat(body).toString());
            });
        });
        rea.on('error', (e) => {
            reject(e.message);
        });
        req.end();
    });
};

exports.handler = async (event) => {
    let pass = await getParameterValue('/serivce/password');
    let passValue = JSON.parse(pass).Parameter.Value;
    //passValue has the password value
};
```

#### Code walkthrough:
AWS Parameters and Secrets Lambda extension exposes HTTP endpoint localhost under 2773 port to Lambda function runtime. AWS SESSION_TOKEN is an in-built environment variable populated by AWS internally. If this secret token not passed to HTTP endpoint - a 401 error will occur.

#### Parameter store Securestring value retrieval using extension:
Just add '**&withDecryption=true**' to the suffix of options objects path field-given below:

```
let options = {
        host: 'localhost',
        path: `/systemsmanager/parameters/get?name=${paramName}&withDecryption=true`,
        port: '2773', 
        headers: headers
        method: 'GET',
}
```

Image by <a href="https://pixabay.com/users/radekkulupa-1045852/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1380134">Radosław Kulupa</a> from <a href="https://pixabay.com//?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1380134">Pixabay</a>