Skip to content

Commit 3e94d97

Browse files
committed
Code refactor
1 parent 1c43646 commit 3e94d97

8 files changed

Lines changed: 151 additions & 78 deletions

File tree

src/PowerShell/Constants.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
export class Constants {
2+
static readonly prefix: string = "az_";
3+
static readonly moduleName: string = "Az.Accounts";
4+
static readonly versionPattern = /[0-9]\.[0-9]\.[0-9]/;
5+
6+
static readonly environment: string = "AzureCloud";
7+
static readonly scopeLevel: string = "Subscription";
8+
static readonly scheme: string = "ServicePrincipal";
9+
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
interface IAzurePowerShellSession {
2+
initialize();
3+
login();
4+
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import * as core from '@actions/core';
2+
3+
import Utils from './Utils';
4+
import PowerShellToolRunner from './PowerShellToolRunner';
5+
import ScriptBuilder from './ScriptBuilder';
6+
import { Constants } from './Constants';
7+
8+
export class ServicePrincipalLogin implements IAzurePowerShellSession {
9+
static readonly environment: string = Constants.environment;
10+
static readonly scopeLevel: string = Constants.scopeLevel;
11+
static readonly scheme: string = Constants.scheme;
12+
servicePrincipalId: string;
13+
servicePrincipalKey: string;
14+
tenantId: string;
15+
subscriptionId: string;
16+
17+
constructor(servicePrincipalId: string, servicePrincipalKey: string, tenantId: string, subscriptionId: string) {
18+
this.servicePrincipalId = servicePrincipalId;
19+
this.servicePrincipalKey = servicePrincipalKey;
20+
this.tenantId = tenantId;
21+
this.subscriptionId = subscriptionId;
22+
}
23+
24+
async initialize() {
25+
Utils.setPSModulePath();
26+
const azLatestVersion: string = await Utils.getLatestModule(Constants.moduleName);
27+
core.debug(`Az Module version used: ${azLatestVersion}`);
28+
Utils.setPSModulePath(`${Constants.prefix}${azLatestVersion}`);
29+
}
30+
31+
async login() {
32+
PowerShellToolRunner.init();
33+
const scriptBuilder: ScriptBuilder = new ScriptBuilder();
34+
const script: string = scriptBuilder.getScript(ServicePrincipalLogin.scheme, this.tenantId, this.servicePrincipalId, this.servicePrincipalKey,
35+
this.subscriptionId, ServicePrincipalLogin.environment, ServicePrincipalLogin.scopeLevel);
36+
PowerShellToolRunner.executePowerShellCommand(script);
37+
}
38+
39+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import * as io from '@actions/io';
2+
import * as exec from '@actions/exec';
3+
4+
export default class PowerShellToolRunner {
5+
static psPath: string;
6+
7+
static async init() {
8+
if(!PowerShellToolRunner.psPath) {
9+
PowerShellToolRunner.psPath = await io.which("pwsh", true);
10+
}
11+
}
12+
13+
static async executePowerShellCommand(command: string, options: any = {}) {
14+
try {
15+
await exec.exec(`"${PowerShellToolRunner.psPath}" -Command "${command}"`, [], options);
16+
} catch(error) {
17+
throw new Error(error);
18+
}
19+
}
20+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
export default class ScriptBuilder {
2+
script: string;
3+
getScript(scheme: string, tenantId: string, servicePrincipalId: string, servicePrincipalKey: string, subscriptionId: string, environment: string, scopeLevel: string): string {
4+
this.script += `Clear-AzContext -Scope Process; Clear-AzContext -Scope CurrentUser -Force -ErrorAction SilentlyContinue;`;
5+
if (scheme === "ServicePrincipal") {
6+
this.script += `Connect-AzAccount -ServicePrincipal -Tenant ${tenantId} -Credential \
7+
(New-Object System.Management.Automation.PSCredential('${servicePrincipalId}',(ConvertTo-SecureString ${servicePrincipalKey} -AsPlainText -Force))) \
8+
-Environment ${environment};`;
9+
if (scopeLevel === "Subscription") {
10+
this.script += `Set-AzContext -SubscriptionId ${subscriptionId} -TenantId ${tenantId};`;
11+
}
12+
}
13+
this.script += `Get-AzContext`;
14+
return this.script;
15+
}
16+
}

src/PowerShell/Utilities/Utils.ts

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import * as os from 'os';
2+
import * as exec from '@actions/exec';
3+
import * as io from '@actions/io';
4+
5+
import { Constants } from './Constants';
6+
import PowerShellToolRunner from './PowerShellToolRunner';
7+
8+
export default class Utils {
9+
static async getLatestModule(moduleName: string): Promise<string> {
10+
let output: string = "";
11+
let error: string = "";
12+
const options: any = {
13+
listeners: {
14+
stdout: (data: Buffer) => {
15+
output += data.toString();
16+
},
17+
stderr: (data: Buffer) => {
18+
error += data.toString();
19+
}
20+
}
21+
};
22+
PowerShellToolRunner.init();
23+
await PowerShellToolRunner.executePowerShellCommand(`(Get-Module -Name ${moduleName} -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1).Version.ToString()`, options);
24+
if(!Utils.isValidVersion(output.trim())) {
25+
return "";
26+
}
27+
return output.trim();
28+
}
29+
30+
private static isValidVersion(version: string): boolean {
31+
return !!version.match(Constants.versionPattern);
32+
}
33+
34+
static setPSModulePath(azPSVersion: string = "") {
35+
let modulePath: string = "";
36+
const RUNNER: string = process.env.RUNNER_OS || os.type();
37+
switch (RUNNER) {
38+
case "Linux":
39+
modulePath = `/usr/share/${azPSVersion}:`;
40+
break;
41+
case "Windows":
42+
case "Windows_NT":
43+
modulePath = `C:\\Modules\\${azPSVersion};`;
44+
break;
45+
case "macOS":
46+
case "Darwin":
47+
// TODO: add modulepath
48+
break;
49+
default:
50+
throw new Error("Unknown os");
51+
}
52+
process.env.PSModulePath = `${modulePath}${process.env.PSModulePath}`;
53+
}
54+
}
55+

src/loginAzurePowerShell.ts

Lines changed: 0 additions & 76 deletions
This file was deleted.

src/main.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import * as exec from '@actions/exec';
44
import * as io from '@actions/io';
55

66
import { FormatType, SecretParser } from 'actions-secret-parser';
7-
import { initializeAz } from './loginAzurePowerShell';
7+
import { ServicePrincipalLogin } from './ServicePrincipalLogin';
88

99
var azPath: string;
1010
var prefix = !!process.env.AZURE_HTTP_USER_AGENT ? `${process.env.AZURE_HTTP_USER_AGENT}` : "";
@@ -26,12 +26,18 @@ async function main() {
2626
let servicePrincipalKey = secrets.getSecret("$.clientSecret", true);
2727
let tenantId = secrets.getSecret("$.tenantId", false);
2828
let subscriptionId = secrets.getSecret("$.subscriptionId", false);
29+
const enablePSSession = !!core.getInput('enable-PSSession');
2930
if (!servicePrincipalId || !servicePrincipalKey || !tenantId || !subscriptionId) {
3031
throw new Error("Not all values are present in the creds object. Ensure clientId, clientSecret, tenantId and subscriptionId are supplied.");
3132
}
3233
await executeAzCliCommand(`login --service-principal -u "${servicePrincipalId}" -p "${servicePrincipalKey}" --tenant "${tenantId}"`);
3334
await executeAzCliCommand(`account set --subscription "${subscriptionId}"`);
34-
await initializeAz(servicePrincipalId, servicePrincipalKey, tenantId, subscriptionId);
35+
if (enablePSSession) {
36+
console.log(`Running Azure PS Login`);
37+
const spnlogin: ServicePrincipalLogin = new ServicePrincipalLogin(servicePrincipalId, servicePrincipalKey, tenantId, subscriptionId);
38+
spnlogin.initialize();
39+
spnlogin.login();
40+
}
3541
console.log("Login successful.");
3642
} catch (error) {
3743
core.error("Login failed. Please check the credentials. For more information refer https://aka.ms/create-secrets-for-GitHub-workflows");

0 commit comments

Comments
 (0)