If you follow my tweets/rants you’ll know I’ve been dabbling in NodeJS recently – specifically to build a CLI tool (and potentially more) around some reporting work I’m doing.
One of the features I have in this CLI tool is the ability to self-review local configuration; think git config
of sorts. In my case I’d like to know things about SDK configuration (AWS) and potentially a series of external API dependencies. This is a simple guide to determining how your AWS SDK global config credentials have been configured using native EC6 promises.
I’ve been using ronin as a scaffold for this. And have a simple myapp.js config list
command which lists out details of configuration.
Note: If you want to use ronin you’ll find its undocumented that you need yo installed.
My big question: Is my SDK configured, and how is it configured?
I managed to self-answer my own stack overflow post so I’m writing up a comparison of approaches as a more detailed answer.
From here on in I deep-dive into code (so I’ll forgo my usual rambling commentary)
CLI command using ronin
"use strict";
var Command = require('ronin').Command;
var AWS = require('aws-sdk');
var colors = require('colors');
var List = Command.extend({
desc: 'List current configuration',
run: function() {
// … do cli magic here
}
});
module.exports = List;
From here on – all my cli mojo can be assumed as going in the run() function.
Using Callbacks
The simplest use is to use the resolve(err, provider) callback that the SDK provides. As follows:
/**
* Check in on the AWS config.
* Require AWS env config (not Charles specific)
*/
/*
AWS.config.credentialProvider.resolve(function(err, credential) {
if(credential !== null) {
awsCredential = credential.constructor.name;
}
})
console.log("AWS configured? ", awsCredential ? 'yes'.green : 'no'.red);
if(awsCredential) {
console.log(" Provided by: ", awsCredential);
}
*/
Using promises
Promises lets me run a bunch of potential config checks async (this is just the beginning). Promises are also fun!
new Promise((resolve, reject) => {
AWS.config.credentialProvider.resolve(function(err, credential) {
if (credential !== null) {
resolve(credential.constructor.name);
} else {
reject(err);
}
});
}).then(awsCredential => {
console.log(awsCredential);
console.log("AWS configured? ", awsCredential ? 'yes'.green : 'no'.red);
if (awsCredential) {
console.log(" Provided by: ", awsCredential);
}
})
.catch(err => {
console.log('AWS is not configured!'.red);
});
I was head scratching for a while here so a very big shoutout to Darren who, on approach to midnight, helped me untangle my code. Thanks Darren!