First and foremost, let create SecretsManager.js by AWS Guide
'use strict'
const AWS = require('aws-sdk');
class SecretsManager {
/**
* Uses AWS Secrets Manager to retrieve a secret
*/
static async getSecret (secretName, region){
const config = { region : region }
var secret, decodedBinarySecret;
let secretsManager = new AWS.SecretsManager(config);
try {
let secretValue = await secretsManager.getSecretValue({SecretId: secretName}).promise();
if ('SecretString' in secretValue) {
return secret = secretValue.SecretString;
} else {
let buff = new Buffer(secretValue.SecretBinary, 'base64');
return decodedBinarySecret = buff.toString('ascii');
}
} catch (err) {
if (err.code === 'DecryptionFailureException')
throw err;
else if (err.code === 'InternalServiceErrorException')
throw err;
else if (err.code === 'InvalidParameterException')
throw err;
else if (err.code === 'InvalidRequestException')
throw err;
else if (err.code === 'ResourceNotFoundException')
throw err;
}
}
}
module.exports = SecretsManager;
The next, we will establish a code implementation to process Query Custom (index.js)
const SecretsManager = require('./SecretsManager.js');
var secretName = '<Secret Name>';
var region = '<Region>';
var databaseName = '<Database Name>';
var pg = require('pg');
async function getData(queryString, dbConfig) {
const pool = new pg.Pool(dbConfig);
var response = {
"headers": { "Content-Type" : "application/json" },
"isBase64Encoded": false,
"body": ""
};
let res;
let client;
try {
client = await pool.connect();
res = await client.query(queryString);
if (res.rows.length == 0) {
response.statusCode = 204;
} else {
response.statusCode = 200;
response.body = JSON.stringify(res);
}
} catch (err) {
response.statusCode = 400;
response.body = err;
} finally {
client.release()
}
return response;
}
exports.handler = async (event) => {
var secretValues = await SecretsManager.getSecret(secretName, region);
var dbSecretConfig = JSON.parse(secretValues);
var dbConfig = {
user: dbSecretConfig.username,
password: dbSecretConfig.password,
database: databaseName,
host: dbSecretConfig.host,
port: dbSecretConfig.port
};
if (!event.queryStringParameters || !event.queryStringParameters.QueryString) {
return {
"statusCode": 400,
"body": "Please provide parameter: QueryString"
}
}
const queryString = event.queryStringParameters.QueryString;
return getData(queryString, dbConfig);
};
Using API Gateway to create external Restful API and test with Postman.
?QueryString=select * from flagtick limit 1000