const MsRest = require('ms-rest-azure'); var computeManagementClient = require('azure-arm-compute'); const SUBSCRIPTION_ID = "62ebff8f-c40b-41be-9239-252d6c0c8ad9"; var computeClient; function auth(cb) { if ( computeClient ) { cb(computeClient); } else { MsRest.loginWithMSI({ port: 50342 }, function(err, credentials){ if (err) { console.log("Could not authenticate with Azure", err); return; } computeClient = new computeManagementClient(credentials, SUBSCRIPTION_ID); cb(computeClient); }); } } async function asyncForEach(array, callback) { for (let index = 0; index < array.length; index++) { await callback(array[index], index, array); } } function deallocate(resourceGroupName, cb) { try { console.log("Deallocating VMs for resource group: "+resourceGroupName); auth(async function(computeClient){ let finalResult = await computeClient.virtualMachines.list(resourceGroupName); let out = []; await asyncForEach(finalResult, async function(vm) { let res = await computeClient.virtualMachines.deallocate(resourceGroupName, vm.name); out.push(res); }); console.log("All VMs DEALLOCATED for resource group: "+resourceGroupName); cb(null, out); }) } catch (err) { console.log("Error deallocating VMs for resource group: "+resourceGroupName); cb(err, null); } } function start(resourceGroupName, cb){ try { console.log("Starting VMs for resource group: "+resourceGroupName); auth(async function(computeClient){ let finalResult = await computeClient.virtualMachines.list(resourceGroupName); let out = []; await asyncForEach(finalResult, async function(vm) { let res = await computeClient.virtualMachines.start(resourceGroupName, vm.name); out.push(res); }); console.log("All VMs RUNNING for resource group: "+resourceGroupName); cb(null,out); }); } catch (err) { console.log("Error starting VMs for resource group: "+resourceGroupName); cb(err, null); } } function getResourceGroupVms(resourceGroupName, cb){ auth(function(computeClient){ computeClient.virtualMachines.list(resourceGroupName, cb); }); } function getAllVms(cb){ auth(function(computeClient){ computeClient.virtualMachines.listAll(cb); }); } module.exports.start = start; module.exports.deallocate = deallocate; module.exports.getResourceGroupVms = getResourceGroupVms; module.exports.getAllVms = getAllVms;