Added changes for review comments

This commit is contained in:
Akshaya M
2020-03-20 16:00:28 +05:30
parent a2be320a3e
commit ad3250b83a
9 changed files with 51 additions and 139 deletions

View File

@@ -36,7 +36,7 @@ class ServicePrincipalLogin {
Utils_1.default.setPSModulePath();
const script = new ScriptBuilder_1.default().getLatestModuleScript(Constants_1.default.moduleName);
const outputJson = yield this.getLatestModule(script);
const azLatestVersion = outputJson.Constants.AzPSVersion;
const azLatestVersion = outputJson[Constants_1.default.AzVersion];
if (!(Constants_1.default.Success in outputJson) || !Utils_1.default.isValidVersion(azLatestVersion)) {
throw new Error(`Invalid AzPSVersion: ${azLatestVersion}`);
}
@@ -55,7 +55,7 @@ class ServicePrincipalLogin {
}
};
yield PowerShellToolRunner_1.default.init();
yield PowerShellToolRunner_1.default.executePowerShellCommand(script, options);
yield PowerShellToolRunner_1.default.executePowerShellScriptBlock(script, options);
return JSON.parse(output.trim());
});
}
@@ -78,10 +78,10 @@ class ServicePrincipalLogin {
};
const script = new ScriptBuilder_1.default().getAzPSLoginScript(ServicePrincipalLogin.scheme, this.tenantId, args);
yield PowerShellToolRunner_1.default.init();
yield PowerShellToolRunner_1.default.executePowerShellCommand(script, options);
yield PowerShellToolRunner_1.default.executePowerShellScriptBlock(script, options);
const outputJson = JSON.parse(output.trim());
if (!(Constants_1.default.Success in outputJson)) {
throw new Error(`Azure PowerShell login failed with error: ${outputJson.Constants.Error}`);
throw new Error(`Azure PowerShell login failed with error: ${outputJson[Constants_1.default.Error]}`);
}
});
}

View File

@@ -26,6 +26,11 @@ class PowerShellToolRunner {
}
});
}
static executePowerShellScriptBlock(scriptBlock, options = {}) {
return __awaiter(this, void 0, void 0, function* () {
yield exec.exec(`${PowerShellToolRunner.psPath} -Command`, [scriptBlock], options);
});
}
static executePowerShellCommand(command, options = {}) {
return __awaiter(this, void 0, void 0, function* () {
yield exec.exec(`"${PowerShellToolRunner.psPath}" -Command "${command}"`, [], options);

View File

@@ -22,38 +22,39 @@ class ScriptBuilder {
if (scheme === Constants_1.default.ServicePrincipal) {
command += `Connect-AzAccount -ServicePrincipal -Tenant ${tenantId} -Credential \
(New-Object System.Management.Automation.PSCredential('${args.servicePrincipalId}',(ConvertTo-SecureString ${args.servicePrincipalKey} -AsPlainText -Force))) \
-Environment ${args.environment};`;
-Environment ${args.environment} | out-null;`;
if (args.scopeLevel === Constants_1.default.Subscription) {
command += `Set-AzContext -SubscriptionId ${args.subscriptionId} -TenantId ${tenantId};`;
command += `Set-AzContext -SubscriptionId ${args.subscriptionId} -TenantId ${tenantId} | out-null;`;
}
}
command += `Get-AzContext`;
this.script += `try {
$$ErrorActionPreference = "Stop";
$$output = @{};
$ErrorActionPreference = "Stop"
$WarningPreference = "SilentlyContinue"
$output = @{}
${command}
$$output['${Constants_1.default.Success}'] = "true";
$output['${Constants_1.default.Success}'] = "true"
}
catch {
$$output['${Constants_1.default.Error}'] = $$_.exception.Message;
$output['${Constants_1.default.Error}'] = $_.exception.Message
}
return ConvertTo-Json $$a`;
return ConvertTo-Json $output`;
core.debug(`Azure PowerShell Login Script: ${this.script}`);
return this.script;
}
getLatestModuleScript(moduleName) {
const command = `Get-Module -Name ${moduleName} -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1`;
this.script += `try {
$$ErrorActionPreference = "Stop";
$$output = @{};
$$data = ${command};
$$output['${Constants_1.default.AzVersion}'] = $$data.Version.ToString();
$$output['${Constants_1.default.Success}'] = "true";
$ErrorActionPreference = "Stop"
$WarningPreference = "SilentlyContinue"
$output = @{}
$data = ${command}
$output['${Constants_1.default.AzVersion}'] = $data.Version.ToString()
$output['${Constants_1.default.Success}'] = "true"
}
catch {
$$output['${Constants_1.default.Error}'] = $$_.exception.Message;
$output['${Constants_1.default.Error}'] = $_.exception.Message
}
return ConvertTo-Json $$a`;
return ConvertTo-Json $output`;
core.debug(`GetLatestModuleScript: ${this.script}`);
return this.script;
}

View File

@@ -26,8 +26,7 @@ class Utils {
break;
case "macos":
case "darwin":
// TODO: add modulepath
break;
throw new Error(`OS not supported`);
default:
throw new Error(`Unknown os: ${runner.toLowerCase()}`);
}

View File

@@ -1,96 +0,0 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const os = __importStar(require("os"));
const core = __importStar(require("@actions/core"));
const exec = __importStar(require("@actions/exec"));
const io = __importStar(require("@actions/io"));
var psPath;
exports.initializeAz = (servicePrincipalId, servicePrincipalKey, tenantId, subscriptionId) => __awaiter(void 0, void 0, void 0, function* () {
psPath = yield io.which("pwsh", true);
yield importModule();
yield loginToAzure(servicePrincipalId, servicePrincipalKey, tenantId, subscriptionId);
});
function importModule() {
return __awaiter(this, void 0, void 0, function* () {
setPSModulePath();
const prefix = "az_";
const moduleName = "Az.Accounts";
const azLatestVersion = yield getLatestModule(moduleName);
core.debug(`Az Module version used: ${azLatestVersion}`);
setPSModulePath(`${prefix}${azLatestVersion}`);
});
}
function setPSModulePath(azPSVersion = "") {
let modulePath = "";
const RUNNER = process.env.RUNNER_OS || os.type();
switch (RUNNER) {
case "Linux":
modulePath = `/usr/share/${azPSVersion}:`;
break;
case "Windows":
case "Windows_NT":
modulePath = `C:\\Modules\\${azPSVersion};`;
break;
case "macOS":
case "Darwin":
// TODO: add modulepath
break;
}
process.env.PSModulePath = `${modulePath}${process.env.PSModulePath}`;
}
function getLatestModule(moduleName) {
return __awaiter(this, void 0, void 0, function* () {
let output = "";
let error = "";
let options = {
listeners: {
stdout: (data) => {
output += data.toString();
},
stderr: (data) => {
error += data.toString();
}
}
};
yield executePowerShellCommand(`(Get-Module -Name ${moduleName} -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1).Version.ToString()`, options);
return output.trim();
});
}
function loginToAzure(servicePrincipalId, servicePrincipalKey, tenantId, subscriptionId) {
return __awaiter(this, void 0, void 0, function* () {
const environment = "AzureCloud";
yield executePowerShellCommand(`Clear-AzContext -Scope Process`);
yield executePowerShellCommand(`Clear-AzContext -Scope CurrentUser -Force -ErrorAction SilentlyContinue`);
yield executePowerShellCommand(`Connect-AzAccount -ServicePrincipal -Tenant ${tenantId} -Credential \
(New-Object System.Management.Automation.PSCredential('${servicePrincipalId}',(ConvertTo-SecureString ${servicePrincipalKey} -AsPlainText -Force))) \
-Environment ${environment}`);
yield executePowerShellCommand(`Set-AzContext -SubscriptionId ${subscriptionId} -TenantId ${tenantId}`);
yield executePowerShellCommand(`Get-AzContext`);
});
}
function executePowerShellCommand(command, options = {}) {
return __awaiter(this, void 0, void 0, function* () {
try {
yield exec.exec(`"${psPath}" -Command "${command}"`, [], options);
}
catch (error) {
throw new Error(error);
}
});
}

View File

@@ -25,7 +25,7 @@ export class ServicePrincipalLogin implements IAzurePowerShellSession {
Utils.setPSModulePath();
const script: string = new ScriptBuilder().getLatestModuleScript(Constants.moduleName);
const outputJson = await this.getLatestModule(script);
const azLatestVersion: string = outputJson.Constants.AzPSVersion;
const azLatestVersion: string = outputJson[Constants.AzVersion];
if (!(Constants.Success in outputJson) || !Utils.isValidVersion(azLatestVersion)) {
throw new Error(`Invalid AzPSVersion: ${azLatestVersion}`);
}
@@ -43,7 +43,7 @@ export class ServicePrincipalLogin implements IAzurePowerShellSession {
}
};
await PowerShellToolRunner.init();
await PowerShellToolRunner.executePowerShellCommand(script, options);
await PowerShellToolRunner.executePowerShellScriptBlock(script, options);
return JSON.parse(output.trim());
}
@@ -65,10 +65,10 @@ export class ServicePrincipalLogin implements IAzurePowerShellSession {
}
const script: string = new ScriptBuilder().getAzPSLoginScript(ServicePrincipalLogin.scheme, this.tenantId, args);
await PowerShellToolRunner.init();
await PowerShellToolRunner.executePowerShellCommand(script, options);
await PowerShellToolRunner.executePowerShellScriptBlock(script, options);
const outputJson: any = JSON.parse(output.trim());
if (!(Constants.Success in outputJson)) {
throw new Error(`Azure PowerShell login failed with error: ${outputJson.Constants.Error}`);
throw new Error(`Azure PowerShell login failed with error: ${outputJson[Constants.Error]}`);
}
}

View File

@@ -10,6 +10,10 @@ export default class PowerShellToolRunner {
}
}
static async executePowerShellScriptBlock(scriptBlock: string, options: any = {}) {
await exec.exec(`${PowerShellToolRunner.psPath} -Command`, [scriptBlock], options)
}
static async executePowerShellCommand(command: string, options: any = {}) {
await exec.exec(`"${PowerShellToolRunner.psPath}" -Command "${command}"`, [], options);
}

View File

@@ -11,22 +11,22 @@ export default class ScriptBuilder {
if (scheme === Constants.ServicePrincipal) {
command += `Connect-AzAccount -ServicePrincipal -Tenant ${tenantId} -Credential \
(New-Object System.Management.Automation.PSCredential('${args.servicePrincipalId}',(ConvertTo-SecureString ${args.servicePrincipalKey} -AsPlainText -Force))) \
-Environment ${args.environment};`;
-Environment ${args.environment} | out-null;`;
if (args.scopeLevel === Constants.Subscription) {
command += `Set-AzContext -SubscriptionId ${args.subscriptionId} -TenantId ${tenantId};`;
command += `Set-AzContext -SubscriptionId ${args.subscriptionId} -TenantId ${tenantId} | out-null;`;
}
}
command += `Get-AzContext`;
this.script += `try {
$$ErrorActionPreference = "Stop";
$$output = @{};
$ErrorActionPreference = "Stop"
$WarningPreference = "SilentlyContinue"
$output = @{}
${command}
$$output['${Constants.Success}'] = "true";
$output['${Constants.Success}'] = "true"
}
catch {
$$output['${Constants.Error}'] = $$_.exception.Message;
$output['${Constants.Error}'] = $_.exception.Message
}
return ConvertTo-Json $$a`;
return ConvertTo-Json $output`;
core.debug(`Azure PowerShell Login Script: ${this.script}`);
return this.script;
}
@@ -34,16 +34,17 @@ export default class ScriptBuilder {
getLatestModuleScript(moduleName: string): string {
const command: string = `Get-Module -Name ${moduleName} -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1`;
this.script += `try {
$$ErrorActionPreference = "Stop";
$$output = @{};
$$data = ${command};
$$output['${Constants.AzVersion}'] = $$data.Version.ToString();
$$output['${Constants.Success}'] = "true";
$ErrorActionPreference = "Stop"
$WarningPreference = "SilentlyContinue"
$output = @{}
$data = ${command}
$output['${Constants.AzVersion}'] = $data.Version.ToString()
$output['${Constants.Success}'] = "true"
}
catch {
$$output['${Constants.Error}'] = $$_.exception.Message;
$output['${Constants.Error}'] = $_.exception.Message
}
return ConvertTo-Json $$a`;
return ConvertTo-Json $output`;
core.debug(`GetLatestModuleScript: ${this.script}`);
return this.script;
}

View File

@@ -1,7 +1,6 @@
import * as os from 'os';
import Constants from '../Constants';
import PowerShellToolRunner from './PowerShellToolRunner';
export default class Utils {
static setPSModulePath(azPSVersion: string = "") {
@@ -17,8 +16,7 @@ export default class Utils {
break;
case "macos":
case "darwin":
// TODO: add modulepath
break;
throw new Error(`OS not supported`);
default:
throw new Error(`Unknown os: ${runner.toLowerCase()}`);
}