Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Demonstrates how to programatically call the Azure CLI. The pattern below only works for synchronous invocation where each command is only called after the other completes.
//requires azure and async modules
var util = require('util');
var cli = require('./node_modules/azure-cli/lib/cli');
var async = require('async');
var called = 0;
function initializeCli() {
//setup the cli
cli.exit = function () {
//don't exit
}
}
// args must be cli commands followed by a callback of the form function(error,result)
// each time this is called it takes over the log function for the cli,
// so invokeCli should only get called after the previous invocation finishes
// note: the cli is async (not blocking), however there's no context passed when the log function is called that could correlate
// back to the caller, thus the only way to ensure that is to serialize the calls.
function invokeCli() {
var newArgs = ["node", "azure"];
var args = Array.prototype.slice.call(arguments);
args = newArgs.concat(args.slice(0, arguments.length -1), "--json");
var callback = arguments[arguments.length-1];
//http://stackoverflow.com/users/374773/dandean
if (!(Object.prototype.toString.call(callback) == '[object Function]')) {
var error = "Last parameter must be a callback";
throw error;
}
//only works if you ensure to call invokeCli in a serial fashion.
cli.output.log = function(level, type, data) {
if(type === "table") {
callback(undefined, data);
}
}
cli.output.error = function(message) {
callback(message);
}
cli.parse(args);
}
//example usage
//call this once
initializeCli();
console.log("fetching sites, vm locations, and vm images\n");
//using async here to ensure calls are serialized and avoid the christmas tree of callbacks
async.waterfall([
function(callback) {
invokeCli("site", "list",callback)
},
function(results,callback) {
console.log(results);
invokeCli("vm", "location", "list", callback);
},
function(results,callback) {
console.log(results);
invokeCli("vm", "image", "list", callback);
},
function(results,callback) {
console.log(results);
invokeCli("does_not_exist", callback);
},
function(results,callback) {
console.log("I should not run because the previous function failed");
},
function(results, callback) {
console.log(results);
callback(null, 'done');
}],
function(err, results) {
if(err)
console.log("Error:" + err);
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.