@bitblit/ratchet-aws
Version:
Common tools for use with AWS browser and node
63 lines • 2.71 kB
JavaScript
import { RequireRatchet } from '@bitblit/ratchet-common/lang/require-ratchet';
import { Logger } from '@bitblit/ratchet-common/logger/logger';
import { ErrorRatchet } from '@bitblit/ratchet-common/lang/error-ratchet';
import { PromiseRatchet } from '@bitblit/ratchet-common/lang/promise-ratchet';
import { StringRatchet } from '@bitblit/ratchet-common/lang/string-ratchet';
import { GetParameterCommand, ParameterNotFound, SSMClient } from '@aws-sdk/client-ssm';
export class SsmEnvironmentServiceProvider {
region;
ssmEncrypted;
ssm;
constructor(region = 'us-east-1', ssmEncrypted = true) {
this.region = region;
this.ssmEncrypted = ssmEncrypted;
RequireRatchet.notNullOrUndefined(region);
RequireRatchet.notNullOrUndefined(ssmEncrypted);
this.ssm = new SSMClient({ region: this.region });
}
async fetchConfig(name) {
Logger.silly('SsmEnvironmentServiceProvider fetch for %s', name);
const params = {
Name: name,
WithDecryption: this.ssmEncrypted,
};
let rval = null;
let toParse = null;
try {
const value = await this.ssm.send(new GetParameterCommand(params));
toParse = StringRatchet.trimToNull(value?.Parameter?.Value);
}
catch (err) {
if (err instanceof ParameterNotFound) {
const errMsg = Logger.warn('AWS could not find parameter %s in region %s - are you using the right AWS key?', name, this.region);
throw new Error(errMsg);
}
else if (err.name === 'CredentialsProviderError') {
Logger.warn('Token is expired - if on SSO cli try "aws sso login"');
throw err;
}
else if ((ErrorRatchet.safeStringifyErr(err) || '').toLowerCase().indexOf('throttl') > -1) {
Logger.warn('Throttled while trying to read parameters - waiting 1 second before allowing retry');
await PromiseRatchet.wait(1_000);
}
else {
Logger.error('Final environment fetch error (cannot retry) : %s', err, err);
throw err;
}
}
if (toParse) {
try {
rval = JSON.parse(toParse);
}
catch (err) {
Logger.error('Failed to read env - null or invalid JSON : %s : %s', err, toParse, err);
throw err;
}
}
else {
throw ErrorRatchet.fErr('Could not find system parameter with name : %s in this account', name);
}
return rval;
}
}
//# sourceMappingURL=ssm-environment-service-provider.js.map