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 Radosław Kulupa from Pixabay
Top comments (0)