public
Last active

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.

  • Download Gist
azure-cli-automation.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
//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);
}
);

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.