Skip to content

Instantly share code, notes, and snippets.

@aroslov
Last active June 3, 2019 10:46
Show Gist options
  • Save aroslov/d24f689a39555e46117cc6cd588584cf to your computer and use it in GitHub Desktop.
Save aroslov/d24f689a39555e46117cc6cd588584cf to your computer and use it in GitHub Desktop.
Lazy Parameter from AWS SSM
import { getDbConnection } from 'dbConnection.service';
getDbConnection().then(connection => { // do something });
import { warn } from 'lib/logger';
import * as AWS from 'aws-sdk';
const ssm = new AWS.SSM();
function getParameterPath(name: string, environment: string) {
return `/my-app/${environment}/${name}`;
}
export function getParameterFromSsm(name: string, environment: string, defaultValue: string): Promise<string> {
return new Promise<string>((resolve) => {
ssm.getParameter(
{
Name: getParameterPath(name, environment),
WithDecryption: true,
},
(err, data) => {
if (err || !data || !data.Parameter.Value) {
warn(`Unable to read ${name} parameter from AWS SSM`, err);
return resolve(defaultValue);
}
return resolve(data.Parameter.Value);
});
});
}
export const dbUsername = new LazyParameter('DB_USERNAME');
export const dbPassword = new LazyParameter('DB_PASSWORD');
import { dbUsername, dbPassword } from 'config';
export async function getDbConnection() {
return new DbConnection(await dbUsername.get(), await dbPassword.get())
}
import { getParameterFromSsm } from 'aws-ssm.sdk'
function getParameterValue(name: string, defaultValue: string) {
return process.env[name] || getParameterFromSsm(name, defaultValue);
}
export class LazyParameter extends LazyValue<string> {
constructor(name: string, defaultValue?: string) {
super(async () => {
return getParameterValue(name, defaultValue);
});
}
}
export class LazyValue<T> {
private value: T;
constructor(private init: () => Promise<T>) {}
async get(): Promise<T> {
if (!this.value) {
this.value = await this.init();
}
return this.value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment