removed comments and removed powershell folder

This commit is contained in:
Atharva Mulmuley
2021-04-28 16:12:56 +05:30
parent b182570c21
commit 04f4eba620
15 changed files with 4 additions and 522 deletions

View File

@@ -1,13 +0,0 @@
export default class Constants {
static readonly prefix: string = "az_";
static readonly moduleName: string = "Az.Accounts";
static readonly versionPattern = /[0-9]\.[0-9]\.[0-9]/;
static readonly AzureCloud: string = "AzureCloud";
static readonly Subscription: string = "Subscription";
static readonly ServicePrincipal: string = "ServicePrincipal";
static readonly Success: string = "Success";
static readonly Error: string = "Error";
static readonly AzVersion: string = "AzVersion";
}

View File

@@ -1,4 +0,0 @@
interface IAzurePowerShellSession {
initialize();
login();
}

View File

@@ -1,71 +0,0 @@
import * as core from '@actions/core';
import Utils from './Utilities/Utils';
import PowerShellToolRunner from './Utilities/PowerShellToolRunner';
import ScriptBuilder from './Utilities/ScriptBuilder';
import Constants from './Constants';
export class ServicePrincipalLogin implements IAzurePowerShellSession {
static readonly scopeLevel: string = Constants.Subscription;
static readonly scheme: string = Constants.ServicePrincipal;
environment: string;
servicePrincipalId: string;
servicePrincipalKey: string;
tenantId: string;
subscriptionId: string;
resourceManagerEndpointUrl: string;
allowNoSubscriptionsLogin: boolean;
constructor(servicePrincipalId: string,
servicePrincipalKey: string,
tenantId: string,
subscriptionId: string,
allowNoSubscriptionsLogin: boolean,
environment: string,
resourceManagerEndpointUrl: string) {
this.servicePrincipalId = servicePrincipalId;
this.servicePrincipalKey = servicePrincipalKey;
this.tenantId = tenantId;
this.subscriptionId = subscriptionId;
this.environment = environment;
this.resourceManagerEndpointUrl = resourceManagerEndpointUrl;
this.allowNoSubscriptionsLogin = allowNoSubscriptionsLogin;
}
async initialize() {
Utils.setPSModulePath();
const azLatestVersion: string = await Utils.getLatestModule(Constants.moduleName);
core.debug(`Az Module version used: ${azLatestVersion}`);
Utils.setPSModulePath(`${Constants.prefix}${azLatestVersion}`);
}
async login() {
let output: string = "";
const options: any = {
listeners: {
stdout: (data: Buffer) => {
output += data.toString();
}
}
};
const args: any = {
servicePrincipalId: this.servicePrincipalId,
servicePrincipalKey: this.servicePrincipalKey,
subscriptionId: this.subscriptionId,
environment: this.environment,
scopeLevel: ServicePrincipalLogin.scopeLevel,
allowNoSubscriptionsLogin: this.allowNoSubscriptionsLogin,
resourceManagerEndpointUrl: this.resourceManagerEndpointUrl
}
const script: string = new ScriptBuilder().getAzPSLoginScript(ServicePrincipalLogin.scheme, this.tenantId, args);
await PowerShellToolRunner.init();
await PowerShellToolRunner.executePowerShellScriptBlock(script, options);
const result: any = JSON.parse(output.trim());
if (!(Constants.Success in result)) {
throw new Error(`Azure PowerShell login failed with error: ${result[Constants.Error]}`);
}
console.log(`Azure PowerShell session successfully initialized`);
}
}

View File

@@ -1,16 +0,0 @@
import * as io from '@actions/io';
import * as exec from '@actions/exec';
export default class PowerShellToolRunner {
static psPath: string;
static async init() {
if(!PowerShellToolRunner.psPath) {
PowerShellToolRunner.psPath = await io.which("pwsh", true);
}
}
static async executePowerShellScriptBlock(scriptBlock: string, options: any = {}) {
await exec.exec(`"${PowerShellToolRunner.psPath}" -Command`, [scriptBlock], options)
}
}

View File

@@ -1,54 +0,0 @@
import * as core from '@actions/core';
import Constants from "../Constants";
export default class ScriptBuilder {
script: string = "";
getAzPSLoginScript(scheme: string, tenantId: string, args: any): string {
let command = `Clear-AzContext -Scope Process;
Clear-AzContext -Scope CurrentUser -Force -ErrorAction SilentlyContinue;`;
if (scheme === Constants.ServicePrincipal) {
if (args.environment.toLowerCase() == "azurestack") {
command += `Add-AzEnvironment -Name ${args.environment} -ARMEndpoint ${args.resourceManagerEndpointUrl} | out-null;`;
}
command += `Connect-AzAccount -ServicePrincipal -Tenant '${tenantId}' -Credential \
(New-Object System.Management.Automation.PSCredential('${args.servicePrincipalId}',(ConvertTo-SecureString '${args.servicePrincipalKey.replace("'", "''")}' -AsPlainText -Force))) \
-Environment '${args.environment}' | out-null;`;
if (args.scopeLevel === Constants.Subscription && !args.allowNoSubscriptionsLogin) {
command += `Set-AzContext -SubscriptionId '${args.subscriptionId}' -TenantId '${tenantId}' | out-null;`;
}
}
this.script += `try {
$ErrorActionPreference = "Stop"
$WarningPreference = "SilentlyContinue"
$output = @{}
${command}
$output['${Constants.Success}'] = "true"
}
catch {
$output['${Constants.Error}'] = $_.exception.Message
}
return ConvertTo-Json $output`;
core.debug(`Azure PowerShell Login Script: ${this.script}`);
return this.script;
}
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"
$WarningPreference = "SilentlyContinue"
$output = @{}
$data = ${command}
$output['${Constants.AzVersion}'] = $data.Version.ToString()
$output['${Constants.Success}'] = "true"
}
catch {
$output['${Constants.Error}'] = $_.exception.Message
}
return ConvertTo-Json $output`;
core.debug(`GetLatestModuleScript: ${this.script}`);
return this.script;
}
}

View File

@@ -1,61 +0,0 @@
import * as os from 'os';
import Constants from '../Constants';
import ScriptBuilder from './ScriptBuilder';
import PowerShellToolRunner from './PowerShellToolRunner';
export default class Utils {
/**
* Add the folder path where Az modules are present to PSModulePath based on runner
* @param azPSVersion
* If azPSVersion is empty, folder path in which all Az modules are present are set
* If azPSVersion is not empty, folder path of exact Az module version is set
*/
static setPSModulePath(azPSVersion: string = "") {
let modulePath: string = "";
const runner: string = process.env.RUNNER_OS || os.type();
switch (runner.toLowerCase()) {
case "linux":
modulePath = `/usr/share/${azPSVersion}:`;
break;
case "windows":
case "windows_nt":
modulePath = `C:\\Modules\\${azPSVersion};`;
break;
case "macos":
case "darwin":
throw new Error(`OS not supported`);
default:
throw new Error(`Unknown os: ${runner.toLowerCase()}`);
}
process.env.PSModulePath = `${modulePath}${process.env.PSModulePath}`;
}
static async getLatestModule(moduleName: string): Promise<string> {
let output: string = "";
const options: any = {
listeners: {
stdout: (data: Buffer) => {
output += data.toString();
}
}
};
await PowerShellToolRunner.init();
await PowerShellToolRunner.executePowerShellScriptBlock(new ScriptBuilder()
.getLatestModuleScript(moduleName), options);
const result = JSON.parse(output.trim());
if (!(Constants.Success in result)) {
throw new Error(result[Constants.Error]);
}
const azLatestVersion: string = result[Constants.AzVersion];
if (!Utils.isValidVersion(azLatestVersion)) {
throw new Error(`Invalid AzPSVersion: ${azLatestVersion}`);
}
return azLatestVersion;
}
static isValidVersion(version: string): boolean {
return !!version.match(Constants.versionPattern);
}
}

View File

@@ -2,7 +2,6 @@ import * as core from '@actions/core';
import * as exec from '@actions/exec';
import * as io from '@actions/io';
import { FormatType, SecretParser } from 'actions-secret-parser';
import { ServicePrincipalLogin } from './PowerShell/ServicePrincipalLogin';
var azPath: string;
var prefix = !!process.env.AZURE_HTTP_USER_AGENT ? `${process.env.AZURE_HTTP_USER_AGENT}` : "";
@@ -47,8 +46,7 @@ export async function main() {
let subscriptionId = secrets.getSecret("$.subscriptionId", false);
let resourceManagerEndpointUrl = secrets.getSecret("$.resourceManagerEndpointUrl", false);
let environment = core.getInput("environment").toLowerCase();
// const enableAzPSSession = core.getInput('enable-AzPSSession').toLowerCase() === "true";
// const allowNoSubscriptionsLogin = core.getInput('allow-no-subscriptions').toLowerCase() === "true";
if (!servicePrincipalId || !servicePrincipalKey || !tenantId) {
throw new Error("Not all values are present in the creds object. Ensure clientId, clientSecret and tenantId are supplied.");
@@ -98,20 +96,7 @@ export async function main() {
await executeAzCliCommand(`cloud set -n "${environment}"`, false);
console.log(`Done setting cloud: "${environment}"`);
// Attempting Az cli login
// if (allowNoSubscriptionsLogin) {
// let args = [
// "--allow-no-subscriptions",
// "--service-principal",
// "-u", servicePrincipalId,
// "-p", servicePrincipalKey,
// "--tenant", tenantId
// ];
// await executeAzCliCommand(`login`, true, {}, args);
// }
// else {
// }
let args = [
"--service-principal",
"-u", servicePrincipalId,
@@ -126,20 +111,7 @@ export async function main() {
await executeAzCliCommand(`account set`, true, {}, args);
isAzCLISuccess = true;
// if (enableAzPSSession) {
// // Attempting Az PS login
// console.log(`Running Azure PS Login`);
// const spnlogin: ServicePrincipalLogin = new ServicePrincipalLogin(
// servicePrincipalId,
// servicePrincipalKey,
// tenantId,
// subscriptionId,
// allowNoSubscriptionsLogin,
// environment,
// resourceManagerEndpointUrl);
// await spnlogin.initialize();
// await spnlogin.login();
// }
console.log("Login successful.");
}
@@ -147,9 +119,6 @@ export async function main() {
if (!isAzCLISuccess) {
core.error("Az CLI Login failed. Please check the credentials. For more information refer https://aka.ms/create-secrets-for-GitHub-workflows");
}
// else {
// core.error(`Azure PowerShell Login failed. Please check the credentials. For more information refer https://aka.ms/create-secrets-for-GitHub-workflows"`);
// }
core.setFailed(error);
}
finally {
@@ -174,4 +143,3 @@ export async function executeAzCliCommand(
}
}
//main();