Keep your database config options in AWS Parameter Store

mmontoya
1 min readApr 3, 2019

I don’t like to have a passwords.yml file hanging around so:

import * as AWS from “aws-sdk”;
import * as path from “path”;
AWS.config.update({ region: “us-east-1” });interface IGenericType {
[key: string]: string | object | number | boolean
}
const STAGE: string = process.env.STAGE;async function getConnection(): Promise<any> {
const params: any = await storeParameters();
const debug: boolean = STAGE === “production” ? false : true;
const dbValues: any = getValues(params.Parameters);const config: IGenericType = {
client: “postgresql”,
connection: {host: dbValues.host, user: dbValues.user, database: dbValues.database, password: dbValues.password
},
debug,
pool: {
min: 2,
max: 10
},
migrations: {
tableName: “knex_migrations”,
directory: path.join(__dirname, “lib”, “migrations”)
},
seeds: {
directory: path.join(__dirname, “lib”, “seeds”)
}
};
console.log(‘ >>> CONFIG: >>>> ‘ + JSON.stringify(config));
return config;
}
async function storeParameters(): Promise<any> {const psHost: string = `/clabe-service/${STAGE}/db/host`; // Set ParameterStore names
const psUser: string = `/clabe-service/${STAGE}/db/user`;
const psDatabase: string = `/clabe-service/${STAGE}/db/database`;
const psPassword: string = `/clabe-service/${STAGE}/db/password`;
const ssm = new AWS.SSM();const query = {
Names: [psHost, psUser, psDatabase, psPassword],
WithDecryption: true
};
const param: any = await ssm.getParameters(query, (err) => {
if (err) {
console.log(“error = %o”, err);
return false;
} else {
return true;
}
}).promise();
return param;
}
function getValues(parameters: Array<any>): any {
let name: string = “”;
return parameters.reduce((result: any, filter: any) => {
name = filter.Name.split(“/”).pop();
result[name] = filter.Value;
return result;
}, {});
}
export default getConnection;

--

--