haufe-azure-arm-utils
Version:
Azure ARM Node Utilities
85 lines (71 loc) • 2.94 kB
JavaScript
;
const debug = require('debug')('haufe-azure-arm-utils:access');
const msRestAzure = require('ms-rest-azure');
const ComputeManagementClient = require('azure-arm-compute');
const ResourceManagementClient = require('azure-arm-resource').ResourceManagementClient;
const access = function () { };
access._credentials = null;
access._subscriptionId = null;
access.getCredentials = (callback) => {
debug('getCredentials()');
if (access._credentials && access._subscriptionId) {
debug('returning cached credentials');
return callback(null, access._credentials, access._subscriptionId);
}
// Log in using service principal
msRestAzure.loginWithServicePrincipalSecret(
process.env.SP_APPID,
process.env.SP_PASSWORD,
process.env.SP_TENANTID,
(err, credentials, subscriptions) => {
if (err) {
return callback(err);
}
debug('loginWithServicePrincipalSecret succeeded');
const existsSubsId = subscriptions.find(s => s.id === process.env.SUBSCRIPTION_ID);
if (!existsSubsId) {
const err = new Error('The given service principal does not have access to subscription ' + process.env.SUBSCRIPTION_ID);
return callback(err);
}
debug('subscription ID matches subscriptions of account');
access._subscriptionId = process.env.SUBSCRIPTION_ID;
access._credentials = credentials;
debug('returning credentials and subscription id');
return callback(null, access._credentials, access._subscriptionId);
});
};
access._computeClient = null;
access.getComputeClient = (callback) => {
debug('getComputeClient()');
if (access._computeClient) {
debug('returning cached computeClient');
return callback(null, access._computeClient);
}
access.getCredentials((err, credentials, subscriptionId) => {
if (err) {
return callback(err);
}
debug('getCredentials succeeded');
access._computeClient = new ComputeManagementClient(credentials, subscriptionId);
debug('returning new compute client');
return callback(null, access._computeClient);
});
};
access._resourceClient = null;
access.getResourceClient = (callback) => {
debug('getResourceClient()');
if (access._resourceClient) {
debug('returning cached resource client');
return callback(null, access._resourceClient);
}
access.getCredentials((err, credentials, subscriptionId) => {
if (err) {
return callback(err);
}
debug('getCredentials succeeded');
access._resourceClient = new ResourceManagementClient(credentials, subscriptionId);
debug('returning new resource client');
return callback(null, access._resourceClient);
});
};
module.exports = access;