From ebd3ce082b304ad6f27eafb49559c0261ea0492a Mon Sep 17 00:00:00 2001 From: Zainuden Veetikadam Date: Mon, 30 Nov 2020 15:15:50 +0530 Subject: [PATCH 01/12] added support for Azure Gov cloud --- lib/main.js | 258 ++++++++++++++++++++++++++++------------------------ src/main.ts | 204 +++++++++++++++++++++-------------------- 2 files changed, 241 insertions(+), 221 deletions(-) diff --git a/lib/main.js b/lib/main.js index 44a041a4..1e8d56a6 100644 --- a/lib/main.js +++ b/lib/main.js @@ -1,121 +1,137 @@ -"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 core = __importStar(require("@actions/core")); -const crypto = __importStar(require("crypto")); -const exec = __importStar(require("@actions/exec")); -const io = __importStar(require("@actions/io")); -const actions_secret_parser_1 = require("actions-secret-parser"); -const ServicePrincipalLogin_1 = require("./PowerShell/ServicePrincipalLogin"); -var azPath; -var prefix = !!process.env.AZURE_HTTP_USER_AGENT ? `${process.env.AZURE_HTTP_USER_AGENT}` : ""; -var azPSHostEnv = !!process.env.AZUREPS_HOST_ENVIRONMENT ? `${process.env.AZUREPS_HOST_ENVIRONMENT}` : ""; -function main() { - return __awaiter(this, void 0, void 0, function* () { - try { - // Set user agent variable - var isAzCLISuccess = false; - let usrAgentRepo = crypto.createHash('sha256').update(`${process.env.GITHUB_REPOSITORY}`).digest('hex'); - let actionName = 'AzureLogin'; - let userAgentString = (!!prefix ? `${prefix}+` : '') + `GITHUBACTIONS/${actionName}@v1_${usrAgentRepo}`; - let azurePSHostEnv = (!!azPSHostEnv ? `${azPSHostEnv}+` : '') + `GITHUBACTIONS/${actionName}@v1_${usrAgentRepo}`; - core.exportVariable('AZURE_HTTP_USER_AGENT', userAgentString); - core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azurePSHostEnv); - azPath = yield io.which("az", true); - yield executeAzCliCommand("--version"); - let creds = core.getInput('creds', { required: true }); - let secrets = new actions_secret_parser_1.SecretParser(creds, actions_secret_parser_1.FormatType.JSON); - let servicePrincipalId = secrets.getSecret("$.clientId", false); - let servicePrincipalKey = secrets.getSecret("$.clientSecret", true); - let tenantId = secrets.getSecret("$.tenantId", false); - let subscriptionId = secrets.getSecret("$.subscriptionId", false); - let resourceManagerEndpointUrl = secrets.getSecret("$.resourceManagerEndpointUrl", false); - let environment = core.getInput("environment"); - const enableAzPSSession = core.getInput('enable-AzPSSession').toLowerCase() === "true"; - if (!servicePrincipalId || !servicePrincipalKey || !tenantId || !subscriptionId) { - throw new Error("Not all values are present in the creds object. Ensure clientId, clientSecret, tenantId and subscriptionId are supplied."); - } - // Attempting Az cli login - if (environment.toLowerCase() == "azurestack") { - if (!resourceManagerEndpointUrl) { - throw new Error("resourceManagerEndpointUrl is a required parameter when environment is defined."); - } - console.log(`Unregistering cloud: "${environment}" first if it exists`); - try { - yield executeAzCliCommand(`cloud set -n AzureCloud`, true); - yield executeAzCliCommand(`cloud unregister -n "${environment}"`, false); - } - catch (error) { - console.log(`Ignore cloud not registered error: "${error}"`); - } - console.log(`Registering cloud: "${environment}" with ARM endpoint: "${resourceManagerEndpointUrl}"`); - try { - let baseUri = resourceManagerEndpointUrl; - if (baseUri.endsWith('/')) { - baseUri = baseUri.substring(0, baseUri.length - 1); // need to remove trailing / from resourceManagerEndpointUrl to correctly derive suffixes below - } - let suffixKeyvault = ".vault" + baseUri.substring(baseUri.indexOf('.')); // keyvault suffix starts with . - let suffixStorage = baseUri.substring(baseUri.indexOf('.') + 1); // storage suffix starts without . - let profileVersion = "2019-03-01-hybrid"; - yield executeAzCliCommand(`cloud register -n "${environment}" --endpoint-resource-manager "${resourceManagerEndpointUrl}" --suffix-keyvault-dns "${suffixKeyvault}" --suffix-storage-endpoint "${suffixStorage}" --profile "${profileVersion}"`, false); - } - catch (error) { - core.error(`Error while trying to register cloud "${environment}": "${error}"`); - } - yield executeAzCliCommand(`cloud set -n "${environment}"`, false); - console.log(`Done registering cloud: "${environment}"`); - } - yield executeAzCliCommand(`login --service-principal -u "${servicePrincipalId}" -p "${servicePrincipalKey}" --tenant "${tenantId}"`, true); - yield executeAzCliCommand(`account set --subscription "${subscriptionId}"`, true); - isAzCLISuccess = true; - if (enableAzPSSession) { - // Attempting Az PS login - console.log(`Running Azure PS Login`); - const spnlogin = new ServicePrincipalLogin_1.ServicePrincipalLogin(servicePrincipalId, servicePrincipalKey, tenantId, subscriptionId, environment, resourceManagerEndpointUrl); - yield spnlogin.initialize(); - yield spnlogin.login(); - } - console.log("Login successful."); - } - catch (error) { - 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 { - // Reset AZURE_HTTP_USER_AGENT - core.exportVariable('AZURE_HTTP_USER_AGENT', prefix); - core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azPSHostEnv); - } - }); -} -function executeAzCliCommand(command, silent) { - return __awaiter(this, void 0, void 0, function* () { - try { - yield exec.exec(`"${azPath}" ${command}`, [], { silent: !!silent }); - } - catch (error) { - throw new Error(error); - } - }); -} -main(); +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +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()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const core = __importStar(require("@actions/core")); +const crypto = __importStar(require("crypto")); +const exec = __importStar(require("@actions/exec")); +const io = __importStar(require("@actions/io")); +const actions_secret_parser_1 = require("actions-secret-parser"); +const ServicePrincipalLogin_1 = require("./PowerShell/ServicePrincipalLogin"); +var azPath; +var prefix = !!process.env.AZURE_HTTP_USER_AGENT ? `${process.env.AZURE_HTTP_USER_AGENT}` : ""; +var azPSHostEnv = !!process.env.AZUREPS_HOST_ENVIRONMENT ? `${process.env.AZUREPS_HOST_ENVIRONMENT}` : ""; +function main() { + return __awaiter(this, void 0, void 0, function* () { + try { + // Set user agent variable + var isAzCLISuccess = false; + let usrAgentRepo = crypto.createHash('sha256').update(`${process.env.GITHUB_REPOSITORY}`).digest('hex'); + let actionName = 'AzureLogin'; + let userAgentString = (!!prefix ? `${prefix}+` : '') + `GITHUBACTIONS/${actionName}@v1_${usrAgentRepo}`; + let azurePSHostEnv = (!!azPSHostEnv ? `${azPSHostEnv}+` : '') + `GITHUBACTIONS/${actionName}@v1_${usrAgentRepo}`; + core.exportVariable('AZURE_HTTP_USER_AGENT', userAgentString); + core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azurePSHostEnv); + azPath = yield io.which("az", true); + yield executeAzCliCommand("--version"); + let creds = core.getInput('creds', { required: true }); + let secrets = new actions_secret_parser_1.SecretParser(creds, actions_secret_parser_1.FormatType.JSON); + let servicePrincipalId = secrets.getSecret("$.clientId", false); + let servicePrincipalKey = secrets.getSecret("$.clientSecret", true); + let tenantId = secrets.getSecret("$.tenantId", false); + let subscriptionId = secrets.getSecret("$.subscriptionId", false); + let resourceManagerEndpointUrl = secrets.getSecret("$.resourceManagerEndpointUrl", false); + let environment = core.getInput("environment"); + const enableAzPSSession = core.getInput('enable-AzPSSession').toLowerCase() === "true"; + if (!servicePrincipalId || !servicePrincipalKey || !tenantId || !subscriptionId) { + throw new Error("Not all values are present in the creds object. Ensure clientId, clientSecret, tenantId and subscriptionId are supplied."); + } + // Attempting Az cli login + if (environment.toLowerCase() == "azurestack") { + if (!resourceManagerEndpointUrl) { + throw new Error("resourceManagerEndpointUrl is a required parameter when environment is defined."); + } + console.log(`Unregistering cloud: "${environment}" first if it exists`); + try { + yield executeAzCliCommand(`cloud set -n AzureCloud`, true); + yield executeAzCliCommand(`cloud unregister -n "${environment}"`, false); + } + catch (error) { + console.log(`Ignore cloud not registered error: "${error}"`); + } + console.log(`Registering cloud: "${environment}" with ARM endpoint: "${resourceManagerEndpointUrl}"`); + try { + let baseUri = resourceManagerEndpointUrl; + if (baseUri.endsWith('/')) { + baseUri = baseUri.substring(0, baseUri.length - 1); // need to remove trailing / from resourceManagerEndpointUrl to correctly derive suffixes below + } + let suffixKeyvault = ".vault" + baseUri.substring(baseUri.indexOf('.')); // keyvault suffix starts with . + let suffixStorage = baseUri.substring(baseUri.indexOf('.') + 1); // storage suffix starts without . + let profileVersion = "2019-03-01-hybrid"; + yield executeAzCliCommand(`cloud register -n "${environment}" --endpoint-resource-manager "${resourceManagerEndpointUrl}" --suffix-keyvault-dns "${suffixKeyvault}" --suffix-storage-endpoint "${suffixStorage}" --profile "${profileVersion}"`, false); + } + catch (error) { + core.error(`Error while trying to register cloud "${environment}": "${error}"`); + } + yield executeAzCliCommand(`cloud set -n "${environment}"`, false); + console.log(`Done registering cloud: "${environment}"`); + } + //setting context to Azure Gov Cloud + if (environment.toLowerCase() == 'azureusgovernment' || environment.toLowerCase() == 'azuregermancloud' || environment.toLowerCase() == 'azurechinacloud' || environment.toLowerCase() == 'azurecloud') { + yield executeAzCliCommand(`cloud set --name "${environment}"`, true); + } + yield executeAzCliCommand(`login --service-principal -u "${servicePrincipalId}" -p "${servicePrincipalKey}" --tenant "${tenantId}"`, true); + yield executeAzCliCommand(`account set --subscription "${subscriptionId}"`, true); + isAzCLISuccess = true; + if (enableAzPSSession) { + // Attempting Az PS login + console.log(`Running Azure PS Login`); + const spnlogin = new ServicePrincipalLogin_1.ServicePrincipalLogin(servicePrincipalId, servicePrincipalKey, tenantId, subscriptionId, environment, resourceManagerEndpointUrl); + yield spnlogin.initialize(); + yield spnlogin.login(); + } + console.log("Login successful."); + } + catch (error) { + 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 { + // Reset AZURE_HTTP_USER_AGENT + core.exportVariable('AZURE_HTTP_USER_AGENT', prefix); + core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azPSHostEnv); + } + }); +} +function executeAzCliCommand(command, silent) { + return __awaiter(this, void 0, void 0, function* () { + try { + yield exec.exec(`"${azPath}" ${command}`, [], { silent: !!silent }); + } + catch (error) { + throw new Error(error); + } + }); +} +main(); diff --git a/src/main.ts b/src/main.ts index 3ae54117..ce03765a 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,101 +1,105 @@ -import * as core from '@actions/core'; -import * as crypto from "crypto"; -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}` : ""; -var azPSHostEnv = !!process.env.AZUREPS_HOST_ENVIRONMENT ? `${process.env.AZUREPS_HOST_ENVIRONMENT}` : ""; - -async function main() { - try { - // Set user agent variable - var isAzCLISuccess = false; - let usrAgentRepo = crypto.createHash('sha256').update(`${process.env.GITHUB_REPOSITORY}`).digest('hex'); - let actionName = 'AzureLogin'; - let userAgentString = (!!prefix ? `${prefix}+` : '') + `GITHUBACTIONS/${actionName}@v1_${usrAgentRepo}`; - let azurePSHostEnv = (!!azPSHostEnv ? `${azPSHostEnv}+` : '') + `GITHUBACTIONS/${actionName}@v1_${usrAgentRepo}`; - core.exportVariable('AZURE_HTTP_USER_AGENT', userAgentString); - core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azurePSHostEnv); - - azPath = await io.which("az", true); - await executeAzCliCommand("--version"); - - let creds = core.getInput('creds', { required: true }); - let secrets = new SecretParser(creds, FormatType.JSON); - let servicePrincipalId = secrets.getSecret("$.clientId", false); - let servicePrincipalKey = secrets.getSecret("$.clientSecret", true); - let tenantId = secrets.getSecret("$.tenantId", false); - let subscriptionId = secrets.getSecret("$.subscriptionId", false); - let resourceManagerEndpointUrl = secrets.getSecret("$.resourceManagerEndpointUrl", false); - let environment = core.getInput("environment"); - const enableAzPSSession = core.getInput('enable-AzPSSession').toLowerCase() === "true"; - if (!servicePrincipalId || !servicePrincipalKey || !tenantId || !subscriptionId) { - throw new Error("Not all values are present in the creds object. Ensure clientId, clientSecret, tenantId and subscriptionId are supplied."); - } - // Attempting Az cli login - if (environment.toLowerCase() == "azurestack") { - if (!resourceManagerEndpointUrl) { - throw new Error("resourceManagerEndpointUrl is a required parameter when environment is defined."); - } - console.log(`Unregistering cloud: "${environment}" first if it exists`); - try { - await executeAzCliCommand(`cloud set -n AzureCloud`, true); - await executeAzCliCommand(`cloud unregister -n "${environment}"`, false); - } catch (error) { - console.log(`Ignore cloud not registered error: "${error}"`); - } - console.log(`Registering cloud: "${environment}" with ARM endpoint: "${resourceManagerEndpointUrl}"`); - try { - let baseUri = resourceManagerEndpointUrl; - if (baseUri.endsWith('/')) { - baseUri = baseUri.substring(0, baseUri.length-1); // need to remove trailing / from resourceManagerEndpointUrl to correctly derive suffixes below - } - let suffixKeyvault = ".vault" + baseUri.substring(baseUri.indexOf('.')); // keyvault suffix starts with . - let suffixStorage = baseUri.substring(baseUri.indexOf('.')+1); // storage suffix starts without . - let profileVersion = "2019-03-01-hybrid"; - await executeAzCliCommand(`cloud register -n "${environment}" --endpoint-resource-manager "${resourceManagerEndpointUrl}" --suffix-keyvault-dns "${suffixKeyvault}" --suffix-storage-endpoint "${suffixStorage}" --profile "${profileVersion}"`, false); - } catch (error) { - core.error(`Error while trying to register cloud "${environment}": "${error}"`); - } - await executeAzCliCommand(`cloud set -n "${environment}"`, false); - console.log(`Done registering cloud: "${environment}"`); - } - await executeAzCliCommand(`login --service-principal -u "${servicePrincipalId}" -p "${servicePrincipalKey}" --tenant "${tenantId}"`, true); - await executeAzCliCommand(`account set --subscription "${subscriptionId}"`, true); - isAzCLISuccess = true; - if (enableAzPSSession) { - // Attempting Az PS login - console.log(`Running Azure PS Login`); - const spnlogin: ServicePrincipalLogin = new ServicePrincipalLogin(servicePrincipalId, servicePrincipalKey, tenantId, subscriptionId, environment, resourceManagerEndpointUrl); - await spnlogin.initialize(); - await spnlogin.login(); - } - console.log("Login successful."); - } catch (error) { - 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 { - // Reset AZURE_HTTP_USER_AGENT - core.exportVariable('AZURE_HTTP_USER_AGENT', prefix); - core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azPSHostEnv); - } -} - -async function executeAzCliCommand(command: string, silent?: boolean) { - try { - await exec.exec(`"${azPath}" ${command}`, [], {silent: !!silent}); - } - catch(error) { - throw new Error(error); - } -} - +import * as core from '@actions/core'; +import * as crypto from "crypto"; +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}` : ""; +var azPSHostEnv = !!process.env.AZUREPS_HOST_ENVIRONMENT ? `${process.env.AZUREPS_HOST_ENVIRONMENT}` : ""; + +async function main() { + try { + // Set user agent variable + var isAzCLISuccess = false; + let usrAgentRepo = crypto.createHash('sha256').update(`${process.env.GITHUB_REPOSITORY}`).digest('hex'); + let actionName = 'AzureLogin'; + let userAgentString = (!!prefix ? `${prefix}+` : '') + `GITHUBACTIONS/${actionName}@v1_${usrAgentRepo}`; + let azurePSHostEnv = (!!azPSHostEnv ? `${azPSHostEnv}+` : '') + `GITHUBACTIONS/${actionName}@v1_${usrAgentRepo}`; + core.exportVariable('AZURE_HTTP_USER_AGENT', userAgentString); + core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azurePSHostEnv); + + azPath = await io.which("az", true); + await executeAzCliCommand("--version"); + + let creds = core.getInput('creds', { required: true }); + let secrets = new SecretParser(creds, FormatType.JSON); + let servicePrincipalId = secrets.getSecret("$.clientId", false); + let servicePrincipalKey = secrets.getSecret("$.clientSecret", true); + let tenantId = secrets.getSecret("$.tenantId", false); + let subscriptionId = secrets.getSecret("$.subscriptionId", false); + let resourceManagerEndpointUrl = secrets.getSecret("$.resourceManagerEndpointUrl", false); + let environment = core.getInput("environment"); + const enableAzPSSession = core.getInput('enable-AzPSSession').toLowerCase() === "true"; + if (!servicePrincipalId || !servicePrincipalKey || !tenantId || !subscriptionId) { + throw new Error("Not all values are present in the creds object. Ensure clientId, clientSecret, tenantId and subscriptionId are supplied."); + } + // Attempting Az cli login + if (environment.toLowerCase() == "azurestack") { + if (!resourceManagerEndpointUrl) { + throw new Error("resourceManagerEndpointUrl is a required parameter when environment is defined."); + } + console.log(`Unregistering cloud: "${environment}" first if it exists`); + try { + await executeAzCliCommand(`cloud set -n AzureCloud`, true); + await executeAzCliCommand(`cloud unregister -n "${environment}"`, false); + } catch (error) { + console.log(`Ignore cloud not registered error: "${error}"`); + } + console.log(`Registering cloud: "${environment}" with ARM endpoint: "${resourceManagerEndpointUrl}"`); + try { + let baseUri = resourceManagerEndpointUrl; + if (baseUri.endsWith('/')) { + baseUri = baseUri.substring(0, baseUri.length-1); // need to remove trailing / from resourceManagerEndpointUrl to correctly derive suffixes below + } + let suffixKeyvault = ".vault" + baseUri.substring(baseUri.indexOf('.')); // keyvault suffix starts with . + let suffixStorage = baseUri.substring(baseUri.indexOf('.')+1); // storage suffix starts without . + let profileVersion = "2019-03-01-hybrid"; + await executeAzCliCommand(`cloud register -n "${environment}" --endpoint-resource-manager "${resourceManagerEndpointUrl}" --suffix-keyvault-dns "${suffixKeyvault}" --suffix-storage-endpoint "${suffixStorage}" --profile "${profileVersion}"`, false); + } catch (error) { + core.error(`Error while trying to register cloud "${environment}": "${error}"`); + } + await executeAzCliCommand(`cloud set -n "${environment}"`, false); + console.log(`Done registering cloud: "${environment}"`); + } + //setting context to Azure Gov Cloud + if (environment.toLowerCase() =='azureusgovernment' || environment.toLowerCase() =='azuregermancloud' || environment.toLowerCase() =='azurechinacloud' || environment.toLowerCase() =='azurecloud' ) { + await executeAzCliCommand(`cloud set --name "${environment}"`, true); + } + await executeAzCliCommand(`login --service-principal -u "${servicePrincipalId}" -p "${servicePrincipalKey}" --tenant "${tenantId}"`, true); + await executeAzCliCommand(`account set --subscription "${subscriptionId}"`, true); + isAzCLISuccess = true; + if (enableAzPSSession) { + // Attempting Az PS login + console.log(`Running Azure PS Login`); + const spnlogin: ServicePrincipalLogin = new ServicePrincipalLogin(servicePrincipalId, servicePrincipalKey, tenantId, subscriptionId, environment, resourceManagerEndpointUrl); + await spnlogin.initialize(); + await spnlogin.login(); + } + console.log("Login successful."); + } catch (error) { + 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 { + // Reset AZURE_HTTP_USER_AGENT + core.exportVariable('AZURE_HTTP_USER_AGENT', prefix); + core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azPSHostEnv); + } +} + +async function executeAzCliCommand(command: string, silent?: boolean) { + try { + await exec.exec(`"${azPath}" ${command}`, [], {silent: !!silent}); + } + catch(error) { + throw new Error(error); + } +} + main(); \ No newline at end of file From 8476f79486cb4f35e0905e6c36199d98b00131c7 Mon Sep 17 00:00:00 2001 From: Zainuden Veetikadam Date: Mon, 30 Nov 2020 15:19:18 +0530 Subject: [PATCH 02/12] changes to Azure cloud --- src/main.ts | 208 ++++++++++++++++++++++++++-------------------------- 1 file changed, 104 insertions(+), 104 deletions(-) diff --git a/src/main.ts b/src/main.ts index ce03765a..9ba368c8 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,105 +1,105 @@ -import * as core from '@actions/core'; -import * as crypto from "crypto"; -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}` : ""; -var azPSHostEnv = !!process.env.AZUREPS_HOST_ENVIRONMENT ? `${process.env.AZUREPS_HOST_ENVIRONMENT}` : ""; - -async function main() { - try { - // Set user agent variable - var isAzCLISuccess = false; - let usrAgentRepo = crypto.createHash('sha256').update(`${process.env.GITHUB_REPOSITORY}`).digest('hex'); - let actionName = 'AzureLogin'; - let userAgentString = (!!prefix ? `${prefix}+` : '') + `GITHUBACTIONS/${actionName}@v1_${usrAgentRepo}`; - let azurePSHostEnv = (!!azPSHostEnv ? `${azPSHostEnv}+` : '') + `GITHUBACTIONS/${actionName}@v1_${usrAgentRepo}`; - core.exportVariable('AZURE_HTTP_USER_AGENT', userAgentString); - core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azurePSHostEnv); - - azPath = await io.which("az", true); - await executeAzCliCommand("--version"); - - let creds = core.getInput('creds', { required: true }); - let secrets = new SecretParser(creds, FormatType.JSON); - let servicePrincipalId = secrets.getSecret("$.clientId", false); - let servicePrincipalKey = secrets.getSecret("$.clientSecret", true); - let tenantId = secrets.getSecret("$.tenantId", false); - let subscriptionId = secrets.getSecret("$.subscriptionId", false); - let resourceManagerEndpointUrl = secrets.getSecret("$.resourceManagerEndpointUrl", false); - let environment = core.getInput("environment"); - const enableAzPSSession = core.getInput('enable-AzPSSession').toLowerCase() === "true"; - if (!servicePrincipalId || !servicePrincipalKey || !tenantId || !subscriptionId) { - throw new Error("Not all values are present in the creds object. Ensure clientId, clientSecret, tenantId and subscriptionId are supplied."); - } - // Attempting Az cli login - if (environment.toLowerCase() == "azurestack") { - if (!resourceManagerEndpointUrl) { - throw new Error("resourceManagerEndpointUrl is a required parameter when environment is defined."); - } - console.log(`Unregistering cloud: "${environment}" first if it exists`); - try { - await executeAzCliCommand(`cloud set -n AzureCloud`, true); - await executeAzCliCommand(`cloud unregister -n "${environment}"`, false); - } catch (error) { - console.log(`Ignore cloud not registered error: "${error}"`); - } - console.log(`Registering cloud: "${environment}" with ARM endpoint: "${resourceManagerEndpointUrl}"`); - try { - let baseUri = resourceManagerEndpointUrl; - if (baseUri.endsWith('/')) { - baseUri = baseUri.substring(0, baseUri.length-1); // need to remove trailing / from resourceManagerEndpointUrl to correctly derive suffixes below - } - let suffixKeyvault = ".vault" + baseUri.substring(baseUri.indexOf('.')); // keyvault suffix starts with . - let suffixStorage = baseUri.substring(baseUri.indexOf('.')+1); // storage suffix starts without . - let profileVersion = "2019-03-01-hybrid"; - await executeAzCliCommand(`cloud register -n "${environment}" --endpoint-resource-manager "${resourceManagerEndpointUrl}" --suffix-keyvault-dns "${suffixKeyvault}" --suffix-storage-endpoint "${suffixStorage}" --profile "${profileVersion}"`, false); - } catch (error) { - core.error(`Error while trying to register cloud "${environment}": "${error}"`); - } - await executeAzCliCommand(`cloud set -n "${environment}"`, false); - console.log(`Done registering cloud: "${environment}"`); - } - //setting context to Azure Gov Cloud - if (environment.toLowerCase() =='azureusgovernment' || environment.toLowerCase() =='azuregermancloud' || environment.toLowerCase() =='azurechinacloud' || environment.toLowerCase() =='azurecloud' ) { - await executeAzCliCommand(`cloud set --name "${environment}"`, true); - } - await executeAzCliCommand(`login --service-principal -u "${servicePrincipalId}" -p "${servicePrincipalKey}" --tenant "${tenantId}"`, true); - await executeAzCliCommand(`account set --subscription "${subscriptionId}"`, true); - isAzCLISuccess = true; - if (enableAzPSSession) { - // Attempting Az PS login - console.log(`Running Azure PS Login`); - const spnlogin: ServicePrincipalLogin = new ServicePrincipalLogin(servicePrincipalId, servicePrincipalKey, tenantId, subscriptionId, environment, resourceManagerEndpointUrl); - await spnlogin.initialize(); - await spnlogin.login(); - } - console.log("Login successful."); - } catch (error) { - 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 { - // Reset AZURE_HTTP_USER_AGENT - core.exportVariable('AZURE_HTTP_USER_AGENT', prefix); - core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azPSHostEnv); - } -} - -async function executeAzCliCommand(command: string, silent?: boolean) { - try { - await exec.exec(`"${azPath}" ${command}`, [], {silent: !!silent}); - } - catch(error) { - throw new Error(error); - } -} - +import * as core from '@actions/core'; +import * as crypto from "crypto"; +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}` : ""; +var azPSHostEnv = !!process.env.AZUREPS_HOST_ENVIRONMENT ? `${process.env.AZUREPS_HOST_ENVIRONMENT}` : ""; + +async function main() { + try { + // Set user agent variable + var isAzCLISuccess = false; + let usrAgentRepo = crypto.createHash('sha256').update(`${process.env.GITHUB_REPOSITORY}`).digest('hex'); + let actionName = 'AzureLogin'; + let userAgentString = (!!prefix ? `${prefix}+` : '') + `GITHUBACTIONS/${actionName}@v1_${usrAgentRepo}`; + let azurePSHostEnv = (!!azPSHostEnv ? `${azPSHostEnv}+` : '') + `GITHUBACTIONS/${actionName}@v1_${usrAgentRepo}`; + core.exportVariable('AZURE_HTTP_USER_AGENT', userAgentString); + core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azurePSHostEnv); + + azPath = await io.which("az", true); + await executeAzCliCommand("--version"); + + let creds = core.getInput('creds', { required: true }); + let secrets = new SecretParser(creds, FormatType.JSON); + let servicePrincipalId = secrets.getSecret("$.clientId", false); + let servicePrincipalKey = secrets.getSecret("$.clientSecret", true); + let tenantId = secrets.getSecret("$.tenantId", false); + let subscriptionId = secrets.getSecret("$.subscriptionId", false); + let resourceManagerEndpointUrl = secrets.getSecret("$.resourceManagerEndpointUrl", false); + let environment = core.getInput("environment"); + const enableAzPSSession = core.getInput('enable-AzPSSession').toLowerCase() === "true"; + if (!servicePrincipalId || !servicePrincipalKey || !tenantId || !subscriptionId) { + throw new Error("Not all values are present in the creds object. Ensure clientId, clientSecret, tenantId and subscriptionId are supplied."); + } + // Attempting Az cli login + if (environment.toLowerCase() == "azurestack") { + if (!resourceManagerEndpointUrl) { + throw new Error("resourceManagerEndpointUrl is a required parameter when environment is defined."); + } + console.log(`Unregistering cloud: "${environment}" first if it exists`); + try { + await executeAzCliCommand(`cloud set -n AzureCloud`, true); + await executeAzCliCommand(`cloud unregister -n "${environment}"`, false); + } catch (error) { + console.log(`Ignore cloud not registered error: "${error}"`); + } + console.log(`Registering cloud: "${environment}" with ARM endpoint: "${resourceManagerEndpointUrl}"`); + try { + let baseUri = resourceManagerEndpointUrl; + if (baseUri.endsWith('/')) { + baseUri = baseUri.substring(0, baseUri.length-1); // need to remove trailing / from resourceManagerEndpointUrl to correctly derive suffixes below + } + let suffixKeyvault = ".vault" + baseUri.substring(baseUri.indexOf('.')); // keyvault suffix starts with . + let suffixStorage = baseUri.substring(baseUri.indexOf('.')+1); // storage suffix starts without . + let profileVersion = "2019-03-01-hybrid"; + await executeAzCliCommand(`cloud register -n "${environment}" --endpoint-resource-manager "${resourceManagerEndpointUrl}" --suffix-keyvault-dns "${suffixKeyvault}" --suffix-storage-endpoint "${suffixStorage}" --profile "${profileVersion}"`, false); + } catch (error) { + core.error(`Error while trying to register cloud "${environment}": "${error}"`); + } + await executeAzCliCommand(`cloud set -n "${environment}"`, false); + console.log(`Done registering cloud: "${environment}"`); + } + //setting context to Azure Gov Cloud + if (environment.toLowerCase() =='azureusgovernment' || environment.toLowerCase() =='azuregermancloud' || environment.toLowerCase() =='azurechinacloud' || environment.toLowerCase() =='azurecloud' ) { + await executeAzCliCommand(`cloud set --name "${environment}"`, true); + } + await executeAzCliCommand(`login --service-principal -u "${servicePrincipalId}" -p "${servicePrincipalKey}" --tenant "${tenantId}"`, true); + await executeAzCliCommand(`account set --subscription "${subscriptionId}"`, true); + isAzCLISuccess = true; + if (enableAzPSSession) { + // Attempting Az PS login + console.log(`Running Azure PS Login`); + const spnlogin: ServicePrincipalLogin = new ServicePrincipalLogin(servicePrincipalId, servicePrincipalKey, tenantId, subscriptionId, environment, resourceManagerEndpointUrl); + await spnlogin.initialize(); + await spnlogin.login(); + } + console.log("Login successful."); + } catch (error) { + 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 { + // Reset AZURE_HTTP_USER_AGENT + core.exportVariable('AZURE_HTTP_USER_AGENT', prefix); + core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azPSHostEnv); + } +} + +async function executeAzCliCommand(command: string, silent?: boolean) { + try { + await exec.exec(`"${azPath}" ${command}`, [], {silent: !!silent}); + } + catch(error) { + throw new Error(error); + } +} + main(); \ No newline at end of file From b5bd60226341762da337a12e66b1e1c685b7b111 Mon Sep 17 00:00:00 2001 From: Zainuden Veetikadam Date: Mon, 30 Nov 2020 15:47:39 +0530 Subject: [PATCH 03/12] az gov cloud changes --- lib/main.js | 274 ++++++++++++++++++++++++++-------------------------- 1 file changed, 137 insertions(+), 137 deletions(-) diff --git a/lib/main.js b/lib/main.js index 1e8d56a6..541a0f36 100644 --- a/lib/main.js +++ b/lib/main.js @@ -1,137 +1,137 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -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()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const core = __importStar(require("@actions/core")); -const crypto = __importStar(require("crypto")); -const exec = __importStar(require("@actions/exec")); -const io = __importStar(require("@actions/io")); -const actions_secret_parser_1 = require("actions-secret-parser"); -const ServicePrincipalLogin_1 = require("./PowerShell/ServicePrincipalLogin"); -var azPath; -var prefix = !!process.env.AZURE_HTTP_USER_AGENT ? `${process.env.AZURE_HTTP_USER_AGENT}` : ""; -var azPSHostEnv = !!process.env.AZUREPS_HOST_ENVIRONMENT ? `${process.env.AZUREPS_HOST_ENVIRONMENT}` : ""; -function main() { - return __awaiter(this, void 0, void 0, function* () { - try { - // Set user agent variable - var isAzCLISuccess = false; - let usrAgentRepo = crypto.createHash('sha256').update(`${process.env.GITHUB_REPOSITORY}`).digest('hex'); - let actionName = 'AzureLogin'; - let userAgentString = (!!prefix ? `${prefix}+` : '') + `GITHUBACTIONS/${actionName}@v1_${usrAgentRepo}`; - let azurePSHostEnv = (!!azPSHostEnv ? `${azPSHostEnv}+` : '') + `GITHUBACTIONS/${actionName}@v1_${usrAgentRepo}`; - core.exportVariable('AZURE_HTTP_USER_AGENT', userAgentString); - core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azurePSHostEnv); - azPath = yield io.which("az", true); - yield executeAzCliCommand("--version"); - let creds = core.getInput('creds', { required: true }); - let secrets = new actions_secret_parser_1.SecretParser(creds, actions_secret_parser_1.FormatType.JSON); - let servicePrincipalId = secrets.getSecret("$.clientId", false); - let servicePrincipalKey = secrets.getSecret("$.clientSecret", true); - let tenantId = secrets.getSecret("$.tenantId", false); - let subscriptionId = secrets.getSecret("$.subscriptionId", false); - let resourceManagerEndpointUrl = secrets.getSecret("$.resourceManagerEndpointUrl", false); - let environment = core.getInput("environment"); - const enableAzPSSession = core.getInput('enable-AzPSSession').toLowerCase() === "true"; - if (!servicePrincipalId || !servicePrincipalKey || !tenantId || !subscriptionId) { - throw new Error("Not all values are present in the creds object. Ensure clientId, clientSecret, tenantId and subscriptionId are supplied."); - } - // Attempting Az cli login - if (environment.toLowerCase() == "azurestack") { - if (!resourceManagerEndpointUrl) { - throw new Error("resourceManagerEndpointUrl is a required parameter when environment is defined."); - } - console.log(`Unregistering cloud: "${environment}" first if it exists`); - try { - yield executeAzCliCommand(`cloud set -n AzureCloud`, true); - yield executeAzCliCommand(`cloud unregister -n "${environment}"`, false); - } - catch (error) { - console.log(`Ignore cloud not registered error: "${error}"`); - } - console.log(`Registering cloud: "${environment}" with ARM endpoint: "${resourceManagerEndpointUrl}"`); - try { - let baseUri = resourceManagerEndpointUrl; - if (baseUri.endsWith('/')) { - baseUri = baseUri.substring(0, baseUri.length - 1); // need to remove trailing / from resourceManagerEndpointUrl to correctly derive suffixes below - } - let suffixKeyvault = ".vault" + baseUri.substring(baseUri.indexOf('.')); // keyvault suffix starts with . - let suffixStorage = baseUri.substring(baseUri.indexOf('.') + 1); // storage suffix starts without . - let profileVersion = "2019-03-01-hybrid"; - yield executeAzCliCommand(`cloud register -n "${environment}" --endpoint-resource-manager "${resourceManagerEndpointUrl}" --suffix-keyvault-dns "${suffixKeyvault}" --suffix-storage-endpoint "${suffixStorage}" --profile "${profileVersion}"`, false); - } - catch (error) { - core.error(`Error while trying to register cloud "${environment}": "${error}"`); - } - yield executeAzCliCommand(`cloud set -n "${environment}"`, false); - console.log(`Done registering cloud: "${environment}"`); - } - //setting context to Azure Gov Cloud - if (environment.toLowerCase() == 'azureusgovernment' || environment.toLowerCase() == 'azuregermancloud' || environment.toLowerCase() == 'azurechinacloud' || environment.toLowerCase() == 'azurecloud') { - yield executeAzCliCommand(`cloud set --name "${environment}"`, true); - } - yield executeAzCliCommand(`login --service-principal -u "${servicePrincipalId}" -p "${servicePrincipalKey}" --tenant "${tenantId}"`, true); - yield executeAzCliCommand(`account set --subscription "${subscriptionId}"`, true); - isAzCLISuccess = true; - if (enableAzPSSession) { - // Attempting Az PS login - console.log(`Running Azure PS Login`); - const spnlogin = new ServicePrincipalLogin_1.ServicePrincipalLogin(servicePrincipalId, servicePrincipalKey, tenantId, subscriptionId, environment, resourceManagerEndpointUrl); - yield spnlogin.initialize(); - yield spnlogin.login(); - } - console.log("Login successful."); - } - catch (error) { - 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 { - // Reset AZURE_HTTP_USER_AGENT - core.exportVariable('AZURE_HTTP_USER_AGENT', prefix); - core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azPSHostEnv); - } - }); -} -function executeAzCliCommand(command, silent) { - return __awaiter(this, void 0, void 0, function* () { - try { - yield exec.exec(`"${azPath}" ${command}`, [], { silent: !!silent }); - } - catch (error) { - throw new Error(error); - } - }); -} -main(); +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +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()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const core = __importStar(require("@actions/core")); +const crypto = __importStar(require("crypto")); +const exec = __importStar(require("@actions/exec")); +const io = __importStar(require("@actions/io")); +const actions_secret_parser_1 = require("actions-secret-parser"); +const ServicePrincipalLogin_1 = require("./PowerShell/ServicePrincipalLogin"); +var azPath; +var prefix = !!process.env.AZURE_HTTP_USER_AGENT ? `${process.env.AZURE_HTTP_USER_AGENT}` : ""; +var azPSHostEnv = !!process.env.AZUREPS_HOST_ENVIRONMENT ? `${process.env.AZUREPS_HOST_ENVIRONMENT}` : ""; +function main() { + return __awaiter(this, void 0, void 0, function* () { + try { + // Set user agent variable + var isAzCLISuccess = false; + let usrAgentRepo = crypto.createHash('sha256').update(`${process.env.GITHUB_REPOSITORY}`).digest('hex'); + let actionName = 'AzureLogin'; + let userAgentString = (!!prefix ? `${prefix}+` : '') + `GITHUBACTIONS/${actionName}@v1_${usrAgentRepo}`; + let azurePSHostEnv = (!!azPSHostEnv ? `${azPSHostEnv}+` : '') + `GITHUBACTIONS/${actionName}@v1_${usrAgentRepo}`; + core.exportVariable('AZURE_HTTP_USER_AGENT', userAgentString); + core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azurePSHostEnv); + azPath = yield io.which("az", true); + yield executeAzCliCommand("--version"); + let creds = core.getInput('creds', { required: true }); + let secrets = new actions_secret_parser_1.SecretParser(creds, actions_secret_parser_1.FormatType.JSON); + let servicePrincipalId = secrets.getSecret("$.clientId", false); + let servicePrincipalKey = secrets.getSecret("$.clientSecret", true); + let tenantId = secrets.getSecret("$.tenantId", false); + let subscriptionId = secrets.getSecret("$.subscriptionId", false); + let resourceManagerEndpointUrl = secrets.getSecret("$.resourceManagerEndpointUrl", false); + let environment = core.getInput("environment"); + const enableAzPSSession = core.getInput('enable-AzPSSession').toLowerCase() === "true"; + if (!servicePrincipalId || !servicePrincipalKey || !tenantId || !subscriptionId) { + throw new Error("Not all values are present in the creds object. Ensure clientId, clientSecret, tenantId and subscriptionId are supplied."); + } + // Attempting Az cli login + if (environment.toLowerCase() == "azurestack") { + if (!resourceManagerEndpointUrl) { + throw new Error("resourceManagerEndpointUrl is a required parameter when environment is defined."); + } + console.log(`Unregistering cloud: "${environment}" first if it exists`); + try { + yield executeAzCliCommand(`cloud set -n AzureCloud`, true); + yield executeAzCliCommand(`cloud unregister -n "${environment}"`, false); + } + catch (error) { + console.log(`Ignore cloud not registered error: "${error}"`); + } + console.log(`Registering cloud: "${environment}" with ARM endpoint: "${resourceManagerEndpointUrl}"`); + try { + let baseUri = resourceManagerEndpointUrl; + if (baseUri.endsWith('/')) { + baseUri = baseUri.substring(0, baseUri.length - 1); // need to remove trailing / from resourceManagerEndpointUrl to correctly derive suffixes below + } + let suffixKeyvault = ".vault" + baseUri.substring(baseUri.indexOf('.')); // keyvault suffix starts with . + let suffixStorage = baseUri.substring(baseUri.indexOf('.') + 1); // storage suffix starts without . + let profileVersion = "2019-03-01-hybrid"; + yield executeAzCliCommand(`cloud register -n "${environment}" --endpoint-resource-manager "${resourceManagerEndpointUrl}" --suffix-keyvault-dns "${suffixKeyvault}" --suffix-storage-endpoint "${suffixStorage}" --profile "${profileVersion}"`, false); + } + catch (error) { + core.error(`Error while trying to register cloud "${environment}": "${error}"`); + } + yield executeAzCliCommand(`cloud set -n "${environment}"`, false); + console.log(`Done registering cloud: "${environment}"`); + } + //setting context to Azure Gov Cloud + if (environment.toLowerCase() == 'azureusgovernment' || environment.toLowerCase() == 'azuregermancloud' || environment.toLowerCase() == 'azurechinacloud' || environment.toLowerCase() == 'azurecloud') { + yield executeAzCliCommand(`cloud set --name "${environment}"`, true); + } + yield executeAzCliCommand(`login --service-principal -u "${servicePrincipalId}" -p "${servicePrincipalKey}" --tenant "${tenantId}"`, true); + yield executeAzCliCommand(`account set --subscription "${subscriptionId}"`, true); + isAzCLISuccess = true; + if (enableAzPSSession) { + // Attempting Az PS login + console.log(`Running Azure PS Login`); + const spnlogin = new ServicePrincipalLogin_1.ServicePrincipalLogin(servicePrincipalId, servicePrincipalKey, tenantId, subscriptionId, environment, resourceManagerEndpointUrl); + yield spnlogin.initialize(); + yield spnlogin.login(); + } + console.log("Login successful."); + } + catch (error) { + 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 { + // Reset AZURE_HTTP_USER_AGENT + core.exportVariable('AZURE_HTTP_USER_AGENT', prefix); + core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azPSHostEnv); + } + }); +} +function executeAzCliCommand(command, silent) { + return __awaiter(this, void 0, void 0, function* () { + try { + yield exec.exec(`"${azPath}" ${command}`, [], { silent: !!silent }); + } + catch (error) { + throw new Error(error); + } + }); +} +main(); From 61f3da0eb117a9f2efbb396ed147318686ddc864 Mon Sep 17 00:00:00 2001 From: Zainuden Veetikadam Date: Sat, 5 Dec 2020 14:21:52 +0530 Subject: [PATCH 04/12] changes as per PR comment --- lib/main.js | 277 ++++++++++++++++++++++++++-------------------------- src/main.ts | 9 +- 2 files changed, 146 insertions(+), 140 deletions(-) diff --git a/lib/main.js b/lib/main.js index 541a0f36..e9762ba5 100644 --- a/lib/main.js +++ b/lib/main.js @@ -1,137 +1,140 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -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()); - }); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const core = __importStar(require("@actions/core")); -const crypto = __importStar(require("crypto")); -const exec = __importStar(require("@actions/exec")); -const io = __importStar(require("@actions/io")); -const actions_secret_parser_1 = require("actions-secret-parser"); -const ServicePrincipalLogin_1 = require("./PowerShell/ServicePrincipalLogin"); -var azPath; -var prefix = !!process.env.AZURE_HTTP_USER_AGENT ? `${process.env.AZURE_HTTP_USER_AGENT}` : ""; -var azPSHostEnv = !!process.env.AZUREPS_HOST_ENVIRONMENT ? `${process.env.AZUREPS_HOST_ENVIRONMENT}` : ""; -function main() { - return __awaiter(this, void 0, void 0, function* () { - try { - // Set user agent variable - var isAzCLISuccess = false; - let usrAgentRepo = crypto.createHash('sha256').update(`${process.env.GITHUB_REPOSITORY}`).digest('hex'); - let actionName = 'AzureLogin'; - let userAgentString = (!!prefix ? `${prefix}+` : '') + `GITHUBACTIONS/${actionName}@v1_${usrAgentRepo}`; - let azurePSHostEnv = (!!azPSHostEnv ? `${azPSHostEnv}+` : '') + `GITHUBACTIONS/${actionName}@v1_${usrAgentRepo}`; - core.exportVariable('AZURE_HTTP_USER_AGENT', userAgentString); - core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azurePSHostEnv); - azPath = yield io.which("az", true); - yield executeAzCliCommand("--version"); - let creds = core.getInput('creds', { required: true }); - let secrets = new actions_secret_parser_1.SecretParser(creds, actions_secret_parser_1.FormatType.JSON); - let servicePrincipalId = secrets.getSecret("$.clientId", false); - let servicePrincipalKey = secrets.getSecret("$.clientSecret", true); - let tenantId = secrets.getSecret("$.tenantId", false); - let subscriptionId = secrets.getSecret("$.subscriptionId", false); - let resourceManagerEndpointUrl = secrets.getSecret("$.resourceManagerEndpointUrl", false); - let environment = core.getInput("environment"); - const enableAzPSSession = core.getInput('enable-AzPSSession').toLowerCase() === "true"; - if (!servicePrincipalId || !servicePrincipalKey || !tenantId || !subscriptionId) { - throw new Error("Not all values are present in the creds object. Ensure clientId, clientSecret, tenantId and subscriptionId are supplied."); - } - // Attempting Az cli login - if (environment.toLowerCase() == "azurestack") { - if (!resourceManagerEndpointUrl) { - throw new Error("resourceManagerEndpointUrl is a required parameter when environment is defined."); - } - console.log(`Unregistering cloud: "${environment}" first if it exists`); - try { - yield executeAzCliCommand(`cloud set -n AzureCloud`, true); - yield executeAzCliCommand(`cloud unregister -n "${environment}"`, false); - } - catch (error) { - console.log(`Ignore cloud not registered error: "${error}"`); - } - console.log(`Registering cloud: "${environment}" with ARM endpoint: "${resourceManagerEndpointUrl}"`); - try { - let baseUri = resourceManagerEndpointUrl; - if (baseUri.endsWith('/')) { - baseUri = baseUri.substring(0, baseUri.length - 1); // need to remove trailing / from resourceManagerEndpointUrl to correctly derive suffixes below - } - let suffixKeyvault = ".vault" + baseUri.substring(baseUri.indexOf('.')); // keyvault suffix starts with . - let suffixStorage = baseUri.substring(baseUri.indexOf('.') + 1); // storage suffix starts without . - let profileVersion = "2019-03-01-hybrid"; - yield executeAzCliCommand(`cloud register -n "${environment}" --endpoint-resource-manager "${resourceManagerEndpointUrl}" --suffix-keyvault-dns "${suffixKeyvault}" --suffix-storage-endpoint "${suffixStorage}" --profile "${profileVersion}"`, false); - } - catch (error) { - core.error(`Error while trying to register cloud "${environment}": "${error}"`); - } - yield executeAzCliCommand(`cloud set -n "${environment}"`, false); - console.log(`Done registering cloud: "${environment}"`); - } - //setting context to Azure Gov Cloud - if (environment.toLowerCase() == 'azureusgovernment' || environment.toLowerCase() == 'azuregermancloud' || environment.toLowerCase() == 'azurechinacloud' || environment.toLowerCase() == 'azurecloud') { - yield executeAzCliCommand(`cloud set --name "${environment}"`, true); - } - yield executeAzCliCommand(`login --service-principal -u "${servicePrincipalId}" -p "${servicePrincipalKey}" --tenant "${tenantId}"`, true); - yield executeAzCliCommand(`account set --subscription "${subscriptionId}"`, true); - isAzCLISuccess = true; - if (enableAzPSSession) { - // Attempting Az PS login - console.log(`Running Azure PS Login`); - const spnlogin = new ServicePrincipalLogin_1.ServicePrincipalLogin(servicePrincipalId, servicePrincipalKey, tenantId, subscriptionId, environment, resourceManagerEndpointUrl); - yield spnlogin.initialize(); - yield spnlogin.login(); - } - console.log("Login successful."); - } - catch (error) { - 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 { - // Reset AZURE_HTTP_USER_AGENT - core.exportVariable('AZURE_HTTP_USER_AGENT', prefix); - core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azPSHostEnv); - } - }); -} -function executeAzCliCommand(command, silent) { - return __awaiter(this, void 0, void 0, function* () { - try { - yield exec.exec(`"${azPath}" ${command}`, [], { silent: !!silent }); - } - catch (error) { - throw new Error(error); - } - }); -} -main(); +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +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()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const core = __importStar(require("@actions/core")); +const crypto = __importStar(require("crypto")); +const exec = __importStar(require("@actions/exec")); +const io = __importStar(require("@actions/io")); +const actions_secret_parser_1 = require("actions-secret-parser"); +const ServicePrincipalLogin_1 = require("./PowerShell/ServicePrincipalLogin"); +var azPath; +var prefix = !!process.env.AZURE_HTTP_USER_AGENT ? `${process.env.AZURE_HTTP_USER_AGENT}` : ""; +var azPSHostEnv = !!process.env.AZUREPS_HOST_ENVIRONMENT ? `${process.env.AZUREPS_HOST_ENVIRONMENT}` : ""; +function main() { + return __awaiter(this, void 0, void 0, function* () { + try { + // Set user agent variable + var isAzCLISuccess = false; + let usrAgentRepo = crypto.createHash('sha256').update(`${process.env.GITHUB_REPOSITORY}`).digest('hex'); + let actionName = 'AzureLogin'; + let userAgentString = (!!prefix ? `${prefix}+` : '') + `GITHUBACTIONS/${actionName}@v1_${usrAgentRepo}`; + let azurePSHostEnv = (!!azPSHostEnv ? `${azPSHostEnv}+` : '') + `GITHUBACTIONS/${actionName}@v1_${usrAgentRepo}`; + core.exportVariable('AZURE_HTTP_USER_AGENT', userAgentString); + core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azurePSHostEnv); + azPath = yield io.which("az", true); + yield executeAzCliCommand("--version"); + let creds = core.getInput('creds', { required: true }); + let secrets = new actions_secret_parser_1.SecretParser(creds, actions_secret_parser_1.FormatType.JSON); + let servicePrincipalId = secrets.getSecret("$.clientId", false); + let servicePrincipalKey = secrets.getSecret("$.clientSecret", true); + let tenantId = secrets.getSecret("$.tenantId", false); + let subscriptionId = secrets.getSecret("$.subscriptionId", false); + let resourceManagerEndpointUrl = secrets.getSecret("$.resourceManagerEndpointUrl", false); + let environment = core.getInput("environment"); + const enableAzPSSession = core.getInput('enable-AzPSSession').toLowerCase() === "true"; + if (!servicePrincipalId || !servicePrincipalKey || !tenantId || !subscriptionId) { + throw new Error("Not all values are present in the creds object. Ensure clientId, clientSecret, tenantId and subscriptionId are supplied."); + } + // Attempting Az cli login + if (environment.toLowerCase() == "azurestack") { + if (!resourceManagerEndpointUrl) { + throw new Error("resourceManagerEndpointUrl is a required parameter when environment is defined."); + } + console.log(`Unregistering cloud: "${environment}" first if it exists`); + try { + yield executeAzCliCommand(`cloud set -n AzureCloud`, true); + yield executeAzCliCommand(`cloud unregister -n "${environment}"`, false); + } + catch (error) { + console.log(`Ignore cloud not registered error: "${error}"`); + } + console.log(`Registering cloud: "${environment}" with ARM endpoint: "${resourceManagerEndpointUrl}"`); + try { + let baseUri = resourceManagerEndpointUrl; + if (baseUri.endsWith('/')) { + baseUri = baseUri.substring(0, baseUri.length - 1); // need to remove trailing / from resourceManagerEndpointUrl to correctly derive suffixes below + } + let suffixKeyvault = ".vault" + baseUri.substring(baseUri.indexOf('.')); // keyvault suffix starts with . + let suffixStorage = baseUri.substring(baseUri.indexOf('.') + 1); // storage suffix starts without . + let profileVersion = "2019-03-01-hybrid"; + yield executeAzCliCommand(`cloud register -n "${environment}" --endpoint-resource-manager "${resourceManagerEndpointUrl}" --suffix-keyvault-dns "${suffixKeyvault}" --suffix-storage-endpoint "${suffixStorage}" --profile "${profileVersion}"`, false); + } + catch (error) { + core.error(`Error while trying to register cloud "${environment}": "${error}"`); + } + yield executeAzCliCommand(`cloud set -n "${environment}"`, false); + console.log(`Done registering cloud: "${environment}"`); + } + //setting context to Azure Gov Cloud + if (environment.toLowerCase() == 'azureusgovernment' || environment.toLowerCase() == 'azuregermancloud' || environment.toLowerCase() == 'azurechinacloud' || environment.toLowerCase() == 'azurecloud') { + yield executeAzCliCommand(`cloud set --name "${environment}"`, true); + } + isAzCLISuccess = true; + if (enableAzPSSession) { + // Attempting Az PS login + console.log(`Running Azure PS Login`); + const spnlogin = new ServicePrincipalLogin_1.ServicePrincipalLogin(servicePrincipalId, servicePrincipalKey, tenantId, subscriptionId, environment, resourceManagerEndpointUrl); + yield spnlogin.initialize(); + yield spnlogin.login(); + } + else { + //else login using az cli + yield executeAzCliCommand(`login --service-principal -u "${servicePrincipalId}" -p "${servicePrincipalKey}" --tenant "${tenantId}"`, true); + yield executeAzCliCommand(`account set --subscription "${subscriptionId}"`, true); + } + console.log("Login successful."); + } + catch (error) { + 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 { + // Reset AZURE_HTTP_USER_AGENT + core.exportVariable('AZURE_HTTP_USER_AGENT', prefix); + core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azPSHostEnv); + } + }); +} +function executeAzCliCommand(command, silent) { + return __awaiter(this, void 0, void 0, function* () { + try { + yield exec.exec(`"${azPath}" ${command}`, [], { silent: !!silent }); + } + catch (error) { + throw new Error(error); + } + }); +} +main(); diff --git a/src/main.ts b/src/main.ts index 9ba368c8..4decb74f 100644 --- a/src/main.ts +++ b/src/main.ts @@ -2,7 +2,6 @@ import * as core from '@actions/core'; import * as crypto from "crypto"; import * as exec from '@actions/exec'; import * as io from '@actions/io'; - import { FormatType, SecretParser } from 'actions-secret-parser'; import { ServicePrincipalLogin } from './PowerShell/ServicePrincipalLogin'; @@ -68,8 +67,7 @@ async function main() { if (environment.toLowerCase() =='azureusgovernment' || environment.toLowerCase() =='azuregermancloud' || environment.toLowerCase() =='azurechinacloud' || environment.toLowerCase() =='azurecloud' ) { await executeAzCliCommand(`cloud set --name "${environment}"`, true); } - await executeAzCliCommand(`login --service-principal -u "${servicePrincipalId}" -p "${servicePrincipalKey}" --tenant "${tenantId}"`, true); - await executeAzCliCommand(`account set --subscription "${subscriptionId}"`, true); + isAzCLISuccess = true; if (enableAzPSSession) { // Attempting Az PS login @@ -78,6 +76,11 @@ async function main() { await spnlogin.initialize(); await spnlogin.login(); } + else{ + //else login using az cli + await executeAzCliCommand(`login --service-principal -u "${servicePrincipalId}" -p "${servicePrincipalKey}" --tenant "${tenantId}"`, true); + await executeAzCliCommand(`account set --subscription "${subscriptionId}"`, true); + } console.log("Login successful."); } catch (error) { if (!isAzCLISuccess) { From dbd3c8ef8df18264db7460e375f71cb2f9b2eb84 Mon Sep 17 00:00:00 2001 From: Zainuden Veetikadam Date: Sat, 5 Dec 2020 15:03:22 +0530 Subject: [PATCH 05/12] chnages to include enum and valdiation --- lib/PowerShell/Enums.js | 11 ++ lib/main.js | 5 +- src/PowerShell/Enums.ts | 7 ++ src/main.ts | 217 ++++++++++++++++++++-------------------- 4 files changed, 131 insertions(+), 109 deletions(-) create mode 100644 lib/PowerShell/Enums.js create mode 100644 src/PowerShell/Enums.ts diff --git a/lib/PowerShell/Enums.js b/lib/PowerShell/Enums.js new file mode 100644 index 00000000..c01f3894 --- /dev/null +++ b/lib/PowerShell/Enums.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AzureCloudName = void 0; +var AzureCloudName; +(function (AzureCloudName) { + AzureCloudName["AzureUSGovernment"] = "azureusgovernment"; + AzureCloudName["AzureChinaCloud"] = "azurechinacloud"; + AzureCloudName["AzureGermanCloud"] = "azuregermancloud"; + AzureCloudName["AzureCloud"] = "azurecloud"; + AzureCloudName["AzureStack"] = "azurestack"; +})(AzureCloudName = exports.AzureCloudName || (exports.AzureCloudName = {})); diff --git a/lib/main.js b/lib/main.js index e9762ba5..b07b4960 100644 --- a/lib/main.js +++ b/lib/main.js @@ -34,6 +34,7 @@ const exec = __importStar(require("@actions/exec")); const io = __importStar(require("@actions/io")); const actions_secret_parser_1 = require("actions-secret-parser"); const ServicePrincipalLogin_1 = require("./PowerShell/ServicePrincipalLogin"); +const Enums_1 = require("./PowerShell/Enums"); var azPath; var prefix = !!process.env.AZURE_HTTP_USER_AGENT ? `${process.env.AZURE_HTTP_USER_AGENT}` : ""; var azPSHostEnv = !!process.env.AZUREPS_HOST_ENVIRONMENT ? `${process.env.AZUREPS_HOST_ENVIRONMENT}` : ""; @@ -93,7 +94,7 @@ function main() { console.log(`Done registering cloud: "${environment}"`); } //setting context to Azure Gov Cloud - if (environment.toLowerCase() == 'azureusgovernment' || environment.toLowerCase() == 'azuregermancloud' || environment.toLowerCase() == 'azurechinacloud' || environment.toLowerCase() == 'azurecloud') { + if (environment.toLowerCase() == Enums_1.AzureCloudName.AzureUSGovernment || environment.toLowerCase() == Enums_1.AzureCloudName.AzureChinaCloud || environment.toLowerCase() == Enums_1.AzureCloudName.AzureGermanCloud || environment.toLowerCase() == Enums_1.AzureCloudName.AzureCloud) { yield executeAzCliCommand(`cloud set --name "${environment}"`, true); } isAzCLISuccess = true; @@ -105,7 +106,7 @@ function main() { yield spnlogin.login(); } else { - //else login using az cli + // login using az cli yield executeAzCliCommand(`login --service-principal -u "${servicePrincipalId}" -p "${servicePrincipalKey}" --tenant "${tenantId}"`, true); yield executeAzCliCommand(`account set --subscription "${subscriptionId}"`, true); } diff --git a/src/PowerShell/Enums.ts b/src/PowerShell/Enums.ts new file mode 100644 index 00000000..9169b9f6 --- /dev/null +++ b/src/PowerShell/Enums.ts @@ -0,0 +1,7 @@ +export enum AzureCloudName { + AzureUSGovernment = "azureusgovernment", + AzureChinaCloud = "azurechinacloud", + AzureGermanCloud = "azuregermancloud", + AzureCloud = "azurecloud", + AzureStack="azurestack" +} \ No newline at end of file diff --git a/src/main.ts b/src/main.ts index 4decb74f..4e475c9a 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,108 +1,111 @@ -import * as core from '@actions/core'; -import * as crypto from "crypto"; -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}` : ""; -var azPSHostEnv = !!process.env.AZUREPS_HOST_ENVIRONMENT ? `${process.env.AZUREPS_HOST_ENVIRONMENT}` : ""; - -async function main() { - try { - // Set user agent variable - var isAzCLISuccess = false; - let usrAgentRepo = crypto.createHash('sha256').update(`${process.env.GITHUB_REPOSITORY}`).digest('hex'); - let actionName = 'AzureLogin'; - let userAgentString = (!!prefix ? `${prefix}+` : '') + `GITHUBACTIONS/${actionName}@v1_${usrAgentRepo}`; - let azurePSHostEnv = (!!azPSHostEnv ? `${azPSHostEnv}+` : '') + `GITHUBACTIONS/${actionName}@v1_${usrAgentRepo}`; - core.exportVariable('AZURE_HTTP_USER_AGENT', userAgentString); - core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azurePSHostEnv); - - azPath = await io.which("az", true); - await executeAzCliCommand("--version"); - - let creds = core.getInput('creds', { required: true }); - let secrets = new SecretParser(creds, FormatType.JSON); - let servicePrincipalId = secrets.getSecret("$.clientId", false); - let servicePrincipalKey = secrets.getSecret("$.clientSecret", true); - let tenantId = secrets.getSecret("$.tenantId", false); - let subscriptionId = secrets.getSecret("$.subscriptionId", false); - let resourceManagerEndpointUrl = secrets.getSecret("$.resourceManagerEndpointUrl", false); - let environment = core.getInput("environment"); - const enableAzPSSession = core.getInput('enable-AzPSSession').toLowerCase() === "true"; - if (!servicePrincipalId || !servicePrincipalKey || !tenantId || !subscriptionId) { - throw new Error("Not all values are present in the creds object. Ensure clientId, clientSecret, tenantId and subscriptionId are supplied."); - } - // Attempting Az cli login - if (environment.toLowerCase() == "azurestack") { - if (!resourceManagerEndpointUrl) { - throw new Error("resourceManagerEndpointUrl is a required parameter when environment is defined."); - } - console.log(`Unregistering cloud: "${environment}" first if it exists`); - try { - await executeAzCliCommand(`cloud set -n AzureCloud`, true); - await executeAzCliCommand(`cloud unregister -n "${environment}"`, false); - } catch (error) { - console.log(`Ignore cloud not registered error: "${error}"`); - } - console.log(`Registering cloud: "${environment}" with ARM endpoint: "${resourceManagerEndpointUrl}"`); - try { - let baseUri = resourceManagerEndpointUrl; - if (baseUri.endsWith('/')) { - baseUri = baseUri.substring(0, baseUri.length-1); // need to remove trailing / from resourceManagerEndpointUrl to correctly derive suffixes below - } - let suffixKeyvault = ".vault" + baseUri.substring(baseUri.indexOf('.')); // keyvault suffix starts with . - let suffixStorage = baseUri.substring(baseUri.indexOf('.')+1); // storage suffix starts without . - let profileVersion = "2019-03-01-hybrid"; - await executeAzCliCommand(`cloud register -n "${environment}" --endpoint-resource-manager "${resourceManagerEndpointUrl}" --suffix-keyvault-dns "${suffixKeyvault}" --suffix-storage-endpoint "${suffixStorage}" --profile "${profileVersion}"`, false); - } catch (error) { - core.error(`Error while trying to register cloud "${environment}": "${error}"`); - } - await executeAzCliCommand(`cloud set -n "${environment}"`, false); - console.log(`Done registering cloud: "${environment}"`); - } - //setting context to Azure Gov Cloud - if (environment.toLowerCase() =='azureusgovernment' || environment.toLowerCase() =='azuregermancloud' || environment.toLowerCase() =='azurechinacloud' || environment.toLowerCase() =='azurecloud' ) { - await executeAzCliCommand(`cloud set --name "${environment}"`, true); - } - - isAzCLISuccess = true; - if (enableAzPSSession) { - // Attempting Az PS login - console.log(`Running Azure PS Login`); - const spnlogin: ServicePrincipalLogin = new ServicePrincipalLogin(servicePrincipalId, servicePrincipalKey, tenantId, subscriptionId, environment, resourceManagerEndpointUrl); - await spnlogin.initialize(); - await spnlogin.login(); - } - else{ - //else login using az cli - await executeAzCliCommand(`login --service-principal -u "${servicePrincipalId}" -p "${servicePrincipalKey}" --tenant "${tenantId}"`, true); - await executeAzCliCommand(`account set --subscription "${subscriptionId}"`, true); - } - console.log("Login successful."); - } catch (error) { - 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 { - // Reset AZURE_HTTP_USER_AGENT - core.exportVariable('AZURE_HTTP_USER_AGENT', prefix); - core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azPSHostEnv); - } -} - -async function executeAzCliCommand(command: string, silent?: boolean) { - try { - await exec.exec(`"${azPath}" ${command}`, [], {silent: !!silent}); - } - catch(error) { - throw new Error(error); - } -} - +import * as core from '@actions/core'; +import * as crypto from "crypto"; +import * as exec from '@actions/exec'; +import * as io from '@actions/io'; +import { FormatType, SecretParser } from 'actions-secret-parser'; +import { ServicePrincipalLogin } from './PowerShell/ServicePrincipalLogin'; +import { AzureCloudName} from './PowerShell/Enums'; + +var azPath: string; +var prefix = !!process.env.AZURE_HTTP_USER_AGENT ? `${process.env.AZURE_HTTP_USER_AGENT}` : ""; +var azPSHostEnv = !!process.env.AZUREPS_HOST_ENVIRONMENT ? `${process.env.AZUREPS_HOST_ENVIRONMENT}` : ""; + +async function main() { + try { + // Set user agent variable + var isAzCLISuccess = false; + let usrAgentRepo = crypto.createHash('sha256').update(`${process.env.GITHUB_REPOSITORY}`).digest('hex'); + let actionName = 'AzureLogin'; + let userAgentString = (!!prefix ? `${prefix}+` : '') + `GITHUBACTIONS/${actionName}@v1_${usrAgentRepo}`; + let azurePSHostEnv = (!!azPSHostEnv ? `${azPSHostEnv}+` : '') + `GITHUBACTIONS/${actionName}@v1_${usrAgentRepo}`; + core.exportVariable('AZURE_HTTP_USER_AGENT', userAgentString); + core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azurePSHostEnv); + + azPath = await io.which("az", true); + await executeAzCliCommand("--version"); + + let creds = core.getInput('creds', { required: true }); + let secrets = new SecretParser(creds, FormatType.JSON); + let servicePrincipalId = secrets.getSecret("$.clientId", false); + let servicePrincipalKey = secrets.getSecret("$.clientSecret", true); + let tenantId = secrets.getSecret("$.tenantId", false); + let subscriptionId = secrets.getSecret("$.subscriptionId", false); + let resourceManagerEndpointUrl = secrets.getSecret("$.resourceManagerEndpointUrl", false); + let environment = core.getInput("environment"); + const enableAzPSSession = core.getInput('enable-AzPSSession').toLowerCase() === "true"; + if (!servicePrincipalId || !servicePrincipalKey || !tenantId || !subscriptionId) { + throw new Error("Not all values are present in the creds object. Ensure clientId, clientSecret, tenantId and subscriptionId are supplied."); + } + + // Attempting Az cli login + if (environment.toLowerCase() == "azurestack") { + if (!resourceManagerEndpointUrl) { + throw new Error("resourceManagerEndpointUrl is a required parameter when environment is defined."); + } + console.log(`Unregistering cloud: "${environment}" first if it exists`); + try { + await executeAzCliCommand(`cloud set -n AzureCloud`, true); + await executeAzCliCommand(`cloud unregister -n "${environment}"`, false); + } catch (error) { + console.log(`Ignore cloud not registered error: "${error}"`); + } + console.log(`Registering cloud: "${environment}" with ARM endpoint: "${resourceManagerEndpointUrl}"`); + try { + let baseUri = resourceManagerEndpointUrl; + if (baseUri.endsWith('/')) { + baseUri = baseUri.substring(0, baseUri.length-1); // need to remove trailing / from resourceManagerEndpointUrl to correctly derive suffixes below + } + let suffixKeyvault = ".vault" + baseUri.substring(baseUri.indexOf('.')); // keyvault suffix starts with . + let suffixStorage = baseUri.substring(baseUri.indexOf('.')+1); // storage suffix starts without . + let profileVersion = "2019-03-01-hybrid"; + await executeAzCliCommand(`cloud register -n "${environment}" --endpoint-resource-manager "${resourceManagerEndpointUrl}" --suffix-keyvault-dns "${suffixKeyvault}" --suffix-storage-endpoint "${suffixStorage}" --profile "${profileVersion}"`, false); + } catch (error) { + core.error(`Error while trying to register cloud "${environment}": "${error}"`); + } + await executeAzCliCommand(`cloud set -n "${environment}"`, false); + console.log(`Done registering cloud: "${environment}"`); + } + + //setting context to Azure Gov Cloud + if (environment.toLowerCase() == AzureCloudName.AzureUSGovernment|| environment.toLowerCase() ==AzureCloudName.AzureChinaCloud || environment.toLowerCase() ==AzureCloudName.AzureGermanCloud || environment.toLowerCase() ==AzureCloudName.AzureCloud ) { + await executeAzCliCommand(`cloud set --name "${environment}"`, true); + } + + isAzCLISuccess = true; + if (enableAzPSSession) { + // Attempting Az PS login + console.log(`Running Azure PS Login`); + const spnlogin: ServicePrincipalLogin = new ServicePrincipalLogin(servicePrincipalId, servicePrincipalKey, tenantId, subscriptionId, environment, resourceManagerEndpointUrl); + await spnlogin.initialize(); + await spnlogin.login(); + } + else{ + // login using az cli + await executeAzCliCommand(`login --service-principal -u "${servicePrincipalId}" -p "${servicePrincipalKey}" --tenant "${tenantId}"`, true); + await executeAzCliCommand(`account set --subscription "${subscriptionId}"`, true); + } + console.log("Login successful."); + } catch (error) { + 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 { + // Reset AZURE_HTTP_USER_AGENT + core.exportVariable('AZURE_HTTP_USER_AGENT', prefix); + core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azPSHostEnv); + } +} + +async function executeAzCliCommand(command: string, silent?: boolean) { + try { + await exec.exec(`"${azPath}" ${command}`, [], {silent: !!silent}); + } + catch(error) { + throw new Error(error); + } +} + main(); \ No newline at end of file From d71ab3132d7079d3c5e9a67491f9df8687781067 Mon Sep 17 00:00:00 2001 From: Zainuden Veetikadam Date: Mon, 7 Dec 2020 17:07:39 +0530 Subject: [PATCH 06/12] changes to include validation --- lib/PowerShell/Constants.js | 1 + lib/main.js | 18 +++++++++------- src/PowerShell/Constants.ts | 1 + src/PowerShell/Enums.ts | 7 ------- src/main.ts | 42 +++++++++++++++++++++++-------------- 5 files changed, 39 insertions(+), 30 deletions(-) delete mode 100644 src/PowerShell/Enums.ts diff --git a/lib/PowerShell/Constants.js b/lib/PowerShell/Constants.js index 98f75ccf..8ba2db80 100644 --- a/lib/PowerShell/Constants.js +++ b/lib/PowerShell/Constants.js @@ -12,3 +12,4 @@ Constants.ServicePrincipal = "ServicePrincipal"; Constants.Success = "Success"; Constants.Error = "Error"; Constants.AzVersion = "AzVersion"; +Constants.AzureSupportedCloudName = ["azureusgovernment", "azurechinacloud", "azuregermancloud", "azurecloud", "azurestack"]; diff --git a/lib/main.js b/lib/main.js index b07b4960..509ce102 100644 --- a/lib/main.js +++ b/lib/main.js @@ -27,6 +27,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; Object.defineProperty(exports, "__esModule", { value: true }); const core = __importStar(require("@actions/core")); const crypto = __importStar(require("crypto")); @@ -34,7 +37,7 @@ const exec = __importStar(require("@actions/exec")); const io = __importStar(require("@actions/io")); const actions_secret_parser_1 = require("actions-secret-parser"); const ServicePrincipalLogin_1 = require("./PowerShell/ServicePrincipalLogin"); -const Enums_1 = require("./PowerShell/Enums"); +const Constants_1 = __importDefault(require("./PowerShell/Constants")); var azPath; var prefix = !!process.env.AZURE_HTTP_USER_AGENT ? `${process.env.AZURE_HTTP_USER_AGENT}` : ""; var azPSHostEnv = !!process.env.AZUREPS_HOST_ENVIRONMENT ? `${process.env.AZUREPS_HOST_ENVIRONMENT}` : ""; @@ -59,12 +62,16 @@ function main() { let subscriptionId = secrets.getSecret("$.subscriptionId", false); let resourceManagerEndpointUrl = secrets.getSecret("$.resourceManagerEndpointUrl", false); let environment = core.getInput("environment"); + environment = environment.toLowerCase(); const enableAzPSSession = core.getInput('enable-AzPSSession').toLowerCase() === "true"; if (!servicePrincipalId || !servicePrincipalKey || !tenantId || !subscriptionId) { throw new Error("Not all values are present in the creds object. Ensure clientId, clientSecret, tenantId and subscriptionId are supplied."); } + if (!Constants_1.default.AzureSupportedCloudName.includes(environment)) { + throw new Error("Unsuppoted value is passed.The list of supported values for environment are ‘azureusgovernment', ‘azurechinacloud’, ‘azuregermancloud’, ‘azurecloud’ or ’azurestack’"); + } // Attempting Az cli login - if (environment.toLowerCase() == "azurestack") { + if (environment == "azurestack") { if (!resourceManagerEndpointUrl) { throw new Error("resourceManagerEndpointUrl is a required parameter when environment is defined."); } @@ -90,13 +97,10 @@ function main() { catch (error) { core.error(`Error while trying to register cloud "${environment}": "${error}"`); } - yield executeAzCliCommand(`cloud set -n "${environment}"`, false); console.log(`Done registering cloud: "${environment}"`); } - //setting context to Azure Gov Cloud - if (environment.toLowerCase() == Enums_1.AzureCloudName.AzureUSGovernment || environment.toLowerCase() == Enums_1.AzureCloudName.AzureChinaCloud || environment.toLowerCase() == Enums_1.AzureCloudName.AzureGermanCloud || environment.toLowerCase() == Enums_1.AzureCloudName.AzureCloud) { - yield executeAzCliCommand(`cloud set --name "${environment}"`, true); - } + yield executeAzCliCommand(`cloud set -n "${environment}"`, false); + console.log(`Done setting cloud: "${environment}"`); isAzCLISuccess = true; if (enableAzPSSession) { // Attempting Az PS login diff --git a/src/PowerShell/Constants.ts b/src/PowerShell/Constants.ts index 9613db1d..572b7b70 100644 --- a/src/PowerShell/Constants.ts +++ b/src/PowerShell/Constants.ts @@ -10,4 +10,5 @@ export default class Constants { static readonly Success: string = "Success"; static readonly Error: string = "Error"; static readonly AzVersion: string = "AzVersion"; + static readonly AzureSupportedCloudName:string[] = ["azureusgovernment", "azurechinacloud", "azuregermancloud","azurecloud","azurestack"]; } \ No newline at end of file diff --git a/src/PowerShell/Enums.ts b/src/PowerShell/Enums.ts deleted file mode 100644 index 9169b9f6..00000000 --- a/src/PowerShell/Enums.ts +++ /dev/null @@ -1,7 +0,0 @@ -export enum AzureCloudName { - AzureUSGovernment = "azureusgovernment", - AzureChinaCloud = "azurechinacloud", - AzureGermanCloud = "azuregermancloud", - AzureCloud = "azurecloud", - AzureStack="azurestack" -} \ No newline at end of file diff --git a/src/main.ts b/src/main.ts index 4e475c9a..cc08ee20 100644 --- a/src/main.ts +++ b/src/main.ts @@ -4,7 +4,7 @@ import * as exec from '@actions/exec'; import * as io from '@actions/io'; import { FormatType, SecretParser } from 'actions-secret-parser'; import { ServicePrincipalLogin } from './PowerShell/ServicePrincipalLogin'; -import { AzureCloudName} from './PowerShell/Enums'; +import Constants from './PowerShell/Constants'; var azPath: string; var prefix = !!process.env.AZURE_HTTP_USER_AGENT ? `${process.env.AZURE_HTTP_USER_AGENT}` : ""; @@ -32,23 +32,31 @@ async function main() { let subscriptionId = secrets.getSecret("$.subscriptionId", false); let resourceManagerEndpointUrl = secrets.getSecret("$.resourceManagerEndpointUrl", false); let environment = core.getInput("environment"); + environment = environment.toLowerCase(); const enableAzPSSession = core.getInput('enable-AzPSSession').toLowerCase() === "true"; if (!servicePrincipalId || !servicePrincipalKey || !tenantId || !subscriptionId) { throw new Error("Not all values are present in the creds object. Ensure clientId, clientSecret, tenantId and subscriptionId are supplied."); } - + + if(!Constants.AzureSupportedCloudName.includes(environment)){ + throw new Error("Unsuppoted value is passed.The list of supported values for environment are ‘azureusgovernment', ‘azurechinacloud’, ‘azuregermancloud’, ‘azurecloud’ or ’azurestack’"); + } + // Attempting Az cli login - if (environment.toLowerCase() == "azurestack") { + if (environment == "azurestack") { if (!resourceManagerEndpointUrl) { throw new Error("resourceManagerEndpointUrl is a required parameter when environment is defined."); } + console.log(`Unregistering cloud: "${environment}" first if it exists`); try { await executeAzCliCommand(`cloud set -n AzureCloud`, true); await executeAzCliCommand(`cloud unregister -n "${environment}"`, false); - } catch (error) { + } + catch (error) { console.log(`Ignore cloud not registered error: "${error}"`); } + console.log(`Registering cloud: "${environment}" with ARM endpoint: "${resourceManagerEndpointUrl}"`); try { let baseUri = resourceManagerEndpointUrl; @@ -59,17 +67,16 @@ async function main() { let suffixStorage = baseUri.substring(baseUri.indexOf('.')+1); // storage suffix starts without . let profileVersion = "2019-03-01-hybrid"; await executeAzCliCommand(`cloud register -n "${environment}" --endpoint-resource-manager "${resourceManagerEndpointUrl}" --suffix-keyvault-dns "${suffixKeyvault}" --suffix-storage-endpoint "${suffixStorage}" --profile "${profileVersion}"`, false); - } catch (error) { + } + catch (error) { core.error(`Error while trying to register cloud "${environment}": "${error}"`); } - await executeAzCliCommand(`cloud set -n "${environment}"`, false); - console.log(`Done registering cloud: "${environment}"`); + + console.log(`Done registering cloud: "${environment}"`) } - - //setting context to Azure Gov Cloud - if (environment.toLowerCase() == AzureCloudName.AzureUSGovernment|| environment.toLowerCase() ==AzureCloudName.AzureChinaCloud || environment.toLowerCase() ==AzureCloudName.AzureGermanCloud || environment.toLowerCase() ==AzureCloudName.AzureCloud ) { - await executeAzCliCommand(`cloud set --name "${environment}"`, true); - } + + await executeAzCliCommand(`cloud set -n "${environment}"`, false); + console.log(`Done setting cloud: "${environment}"`); isAzCLISuccess = true; if (enableAzPSSession) { @@ -79,20 +86,23 @@ async function main() { await spnlogin.initialize(); await spnlogin.login(); } - else{ + else { // login using az cli await executeAzCliCommand(`login --service-principal -u "${servicePrincipalId}" -p "${servicePrincipalKey}" --tenant "${tenantId}"`, true); await executeAzCliCommand(`account set --subscription "${subscriptionId}"`, true); } console.log("Login successful."); - } catch (error) { + } + catch (error) { 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 { + } + 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 { + } + finally { // Reset AZURE_HTTP_USER_AGENT core.exportVariable('AZURE_HTTP_USER_AGENT', prefix); core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azPSHostEnv); From b7f16dbb801c4453237698b939f444d9b8ec8282 Mon Sep 17 00:00:00 2001 From: Zainuden Veetikadam Date: Mon, 7 Dec 2020 17:18:58 +0530 Subject: [PATCH 07/12] changes --- lib/main.js | 2 +- src/main.ts | 240 ++++++++++++++++++++++++++-------------------------- 2 files changed, 121 insertions(+), 121 deletions(-) diff --git a/lib/main.js b/lib/main.js index 509ce102..47200c70 100644 --- a/lib/main.js +++ b/lib/main.js @@ -68,7 +68,7 @@ function main() { throw new Error("Not all values are present in the creds object. Ensure clientId, clientSecret, tenantId and subscriptionId are supplied."); } if (!Constants_1.default.AzureSupportedCloudName.includes(environment)) { - throw new Error("Unsuppoted value is passed.The list of supported values for environment are ‘azureusgovernment', ‘azurechinacloud’, ‘azuregermancloud’, ‘azurecloud’ or ’azurestack’"); + throw new Error("Unsupported value for environment is passed.The list of supported values for environment are ‘azureusgovernment', ‘azurechinacloud’, ‘azuregermancloud’, ‘azurecloud’ or ’azurestack’"); } // Attempting Az cli login if (environment == "azurestack") { diff --git a/src/main.ts b/src/main.ts index cc08ee20..8139be21 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,121 +1,121 @@ -import * as core from '@actions/core'; -import * as crypto from "crypto"; -import * as exec from '@actions/exec'; -import * as io from '@actions/io'; -import { FormatType, SecretParser } from 'actions-secret-parser'; -import { ServicePrincipalLogin } from './PowerShell/ServicePrincipalLogin'; -import Constants from './PowerShell/Constants'; - -var azPath: string; -var prefix = !!process.env.AZURE_HTTP_USER_AGENT ? `${process.env.AZURE_HTTP_USER_AGENT}` : ""; -var azPSHostEnv = !!process.env.AZUREPS_HOST_ENVIRONMENT ? `${process.env.AZUREPS_HOST_ENVIRONMENT}` : ""; - -async function main() { - try { - // Set user agent variable - var isAzCLISuccess = false; - let usrAgentRepo = crypto.createHash('sha256').update(`${process.env.GITHUB_REPOSITORY}`).digest('hex'); - let actionName = 'AzureLogin'; - let userAgentString = (!!prefix ? `${prefix}+` : '') + `GITHUBACTIONS/${actionName}@v1_${usrAgentRepo}`; - let azurePSHostEnv = (!!azPSHostEnv ? `${azPSHostEnv}+` : '') + `GITHUBACTIONS/${actionName}@v1_${usrAgentRepo}`; - core.exportVariable('AZURE_HTTP_USER_AGENT', userAgentString); - core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azurePSHostEnv); - - azPath = await io.which("az", true); - await executeAzCliCommand("--version"); - - let creds = core.getInput('creds', { required: true }); - let secrets = new SecretParser(creds, FormatType.JSON); - let servicePrincipalId = secrets.getSecret("$.clientId", false); - let servicePrincipalKey = secrets.getSecret("$.clientSecret", true); - let tenantId = secrets.getSecret("$.tenantId", false); - let subscriptionId = secrets.getSecret("$.subscriptionId", false); - let resourceManagerEndpointUrl = secrets.getSecret("$.resourceManagerEndpointUrl", false); - let environment = core.getInput("environment"); - environment = environment.toLowerCase(); - const enableAzPSSession = core.getInput('enable-AzPSSession').toLowerCase() === "true"; - if (!servicePrincipalId || !servicePrincipalKey || !tenantId || !subscriptionId) { - throw new Error("Not all values are present in the creds object. Ensure clientId, clientSecret, tenantId and subscriptionId are supplied."); - } - - if(!Constants.AzureSupportedCloudName.includes(environment)){ - throw new Error("Unsuppoted value is passed.The list of supported values for environment are ‘azureusgovernment', ‘azurechinacloud’, ‘azuregermancloud’, ‘azurecloud’ or ’azurestack’"); - } - - // Attempting Az cli login - if (environment == "azurestack") { - if (!resourceManagerEndpointUrl) { - throw new Error("resourceManagerEndpointUrl is a required parameter when environment is defined."); - } - - console.log(`Unregistering cloud: "${environment}" first if it exists`); - try { - await executeAzCliCommand(`cloud set -n AzureCloud`, true); - await executeAzCliCommand(`cloud unregister -n "${environment}"`, false); - } - catch (error) { - console.log(`Ignore cloud not registered error: "${error}"`); - } - - console.log(`Registering cloud: "${environment}" with ARM endpoint: "${resourceManagerEndpointUrl}"`); - try { - let baseUri = resourceManagerEndpointUrl; - if (baseUri.endsWith('/')) { - baseUri = baseUri.substring(0, baseUri.length-1); // need to remove trailing / from resourceManagerEndpointUrl to correctly derive suffixes below - } - let suffixKeyvault = ".vault" + baseUri.substring(baseUri.indexOf('.')); // keyvault suffix starts with . - let suffixStorage = baseUri.substring(baseUri.indexOf('.')+1); // storage suffix starts without . - let profileVersion = "2019-03-01-hybrid"; - await executeAzCliCommand(`cloud register -n "${environment}" --endpoint-resource-manager "${resourceManagerEndpointUrl}" --suffix-keyvault-dns "${suffixKeyvault}" --suffix-storage-endpoint "${suffixStorage}" --profile "${profileVersion}"`, false); - } - catch (error) { - core.error(`Error while trying to register cloud "${environment}": "${error}"`); - } - - console.log(`Done registering cloud: "${environment}"`) - } - - await executeAzCliCommand(`cloud set -n "${environment}"`, false); - console.log(`Done setting cloud: "${environment}"`); - - isAzCLISuccess = true; - if (enableAzPSSession) { - // Attempting Az PS login - console.log(`Running Azure PS Login`); - const spnlogin: ServicePrincipalLogin = new ServicePrincipalLogin(servicePrincipalId, servicePrincipalKey, tenantId, subscriptionId, environment, resourceManagerEndpointUrl); - await spnlogin.initialize(); - await spnlogin.login(); - } - else { - // login using az cli - await executeAzCliCommand(`login --service-principal -u "${servicePrincipalId}" -p "${servicePrincipalKey}" --tenant "${tenantId}"`, true); - await executeAzCliCommand(`account set --subscription "${subscriptionId}"`, true); - } - console.log("Login successful."); - } - catch (error) { - 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 { - // Reset AZURE_HTTP_USER_AGENT - core.exportVariable('AZURE_HTTP_USER_AGENT', prefix); - core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azPSHostEnv); - } -} - -async function executeAzCliCommand(command: string, silent?: boolean) { - try { - await exec.exec(`"${azPath}" ${command}`, [], {silent: !!silent}); - } - catch(error) { - throw new Error(error); - } -} - +import * as core from '@actions/core'; +import * as crypto from "crypto"; +import * as exec from '@actions/exec'; +import * as io from '@actions/io'; +import { FormatType, SecretParser } from 'actions-secret-parser'; +import { ServicePrincipalLogin } from './PowerShell/ServicePrincipalLogin'; +import Constants from './PowerShell/Constants'; + +var azPath: string; +var prefix = !!process.env.AZURE_HTTP_USER_AGENT ? `${process.env.AZURE_HTTP_USER_AGENT}` : ""; +var azPSHostEnv = !!process.env.AZUREPS_HOST_ENVIRONMENT ? `${process.env.AZUREPS_HOST_ENVIRONMENT}` : ""; + +async function main() { + try { + // Set user agent variable + var isAzCLISuccess = false; + let usrAgentRepo = crypto.createHash('sha256').update(`${process.env.GITHUB_REPOSITORY}`).digest('hex'); + let actionName = 'AzureLogin'; + let userAgentString = (!!prefix ? `${prefix}+` : '') + `GITHUBACTIONS/${actionName}@v1_${usrAgentRepo}`; + let azurePSHostEnv = (!!azPSHostEnv ? `${azPSHostEnv}+` : '') + `GITHUBACTIONS/${actionName}@v1_${usrAgentRepo}`; + core.exportVariable('AZURE_HTTP_USER_AGENT', userAgentString); + core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azurePSHostEnv); + + azPath = await io.which("az", true); + await executeAzCliCommand("--version"); + + let creds = core.getInput('creds', { required: true }); + let secrets = new SecretParser(creds, FormatType.JSON); + let servicePrincipalId = secrets.getSecret("$.clientId", false); + let servicePrincipalKey = secrets.getSecret("$.clientSecret", true); + let tenantId = secrets.getSecret("$.tenantId", false); + let subscriptionId = secrets.getSecret("$.subscriptionId", false); + let resourceManagerEndpointUrl = secrets.getSecret("$.resourceManagerEndpointUrl", false); + let environment = core.getInput("environment"); + environment = environment.toLowerCase(); + const enableAzPSSession = core.getInput('enable-AzPSSession').toLowerCase() === "true"; + if (!servicePrincipalId || !servicePrincipalKey || !tenantId || !subscriptionId) { + throw new Error("Not all values are present in the creds object. Ensure clientId, clientSecret, tenantId and subscriptionId are supplied."); + } + + if(!Constants.AzureSupportedCloudName.includes(environment)){ + throw new Error("Unsupported value for environment is passed.The list of supported values for environment are ‘azureusgovernment', ‘azurechinacloud’, ‘azuregermancloud’, ‘azurecloud’ or ’azurestack’"); + } + + // Attempting Az cli login + if (environment == "azurestack") { + if (!resourceManagerEndpointUrl) { + throw new Error("resourceManagerEndpointUrl is a required parameter when environment is defined."); + } + + console.log(`Unregistering cloud: "${environment}" first if it exists`); + try { + await executeAzCliCommand(`cloud set -n AzureCloud`, true); + await executeAzCliCommand(`cloud unregister -n "${environment}"`, false); + } + catch (error) { + console.log(`Ignore cloud not registered error: "${error}"`); + } + + console.log(`Registering cloud: "${environment}" with ARM endpoint: "${resourceManagerEndpointUrl}"`); + try { + let baseUri = resourceManagerEndpointUrl; + if (baseUri.endsWith('/')) { + baseUri = baseUri.substring(0, baseUri.length-1); // need to remove trailing / from resourceManagerEndpointUrl to correctly derive suffixes below + } + let suffixKeyvault = ".vault" + baseUri.substring(baseUri.indexOf('.')); // keyvault suffix starts with . + let suffixStorage = baseUri.substring(baseUri.indexOf('.')+1); // storage suffix starts without . + let profileVersion = "2019-03-01-hybrid"; + await executeAzCliCommand(`cloud register -n "${environment}" --endpoint-resource-manager "${resourceManagerEndpointUrl}" --suffix-keyvault-dns "${suffixKeyvault}" --suffix-storage-endpoint "${suffixStorage}" --profile "${profileVersion}"`, false); + } + catch (error) { + core.error(`Error while trying to register cloud "${environment}": "${error}"`); + } + + console.log(`Done registering cloud: "${environment}"`) + } + + await executeAzCliCommand(`cloud set -n "${environment}"`, false); + console.log(`Done setting cloud: "${environment}"`); + + isAzCLISuccess = true; + if (enableAzPSSession) { + // Attempting Az PS login + console.log(`Running Azure PS Login`); + const spnlogin: ServicePrincipalLogin = new ServicePrincipalLogin(servicePrincipalId, servicePrincipalKey, tenantId, subscriptionId, environment, resourceManagerEndpointUrl); + await spnlogin.initialize(); + await spnlogin.login(); + } + else { + // login using az cli + await executeAzCliCommand(`login --service-principal -u "${servicePrincipalId}" -p "${servicePrincipalKey}" --tenant "${tenantId}"`, true); + await executeAzCliCommand(`account set --subscription "${subscriptionId}"`, true); + } + console.log("Login successful."); + } + catch (error) { + 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 { + // Reset AZURE_HTTP_USER_AGENT + core.exportVariable('AZURE_HTTP_USER_AGENT', prefix); + core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azPSHostEnv); + } +} + +async function executeAzCliCommand(command: string, silent?: boolean) { + try { + await exec.exec(`"${azPath}" ${command}`, [], {silent: !!silent}); + } + catch(error) { + throw new Error(error); + } +} + main(); \ No newline at end of file From 78d65b04b4a0dc799aaf2446412d1fa1389d36e8 Mon Sep 17 00:00:00 2001 From: Zainuden Veetikadam Date: Tue, 8 Dec 2020 10:52:18 +0530 Subject: [PATCH 08/12] deleted Enums.js --- lib/PowerShell/Enums.js | 11 ----------- 1 file changed, 11 deletions(-) delete mode 100644 lib/PowerShell/Enums.js diff --git a/lib/PowerShell/Enums.js b/lib/PowerShell/Enums.js deleted file mode 100644 index c01f3894..00000000 --- a/lib/PowerShell/Enums.js +++ /dev/null @@ -1,11 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.AzureCloudName = void 0; -var AzureCloudName; -(function (AzureCloudName) { - AzureCloudName["AzureUSGovernment"] = "azureusgovernment"; - AzureCloudName["AzureChinaCloud"] = "azurechinacloud"; - AzureCloudName["AzureGermanCloud"] = "azuregermancloud"; - AzureCloudName["AzureCloud"] = "azurecloud"; - AzureCloudName["AzureStack"] = "azurestack"; -})(AzureCloudName = exports.AzureCloudName || (exports.AzureCloudName = {})); From c23434512d9995465fd1318a1b74e56422ce0bd7 Mon Sep 17 00:00:00 2001 From: Zainuden Veetikadam Date: Tue, 8 Dec 2020 14:38:39 +0530 Subject: [PATCH 09/12] changes to constant file --- lib/main.js | 7 ++----- src/PowerShell/Constants.ts | 1 - src/main.ts | 7 ++++--- 3 files changed, 6 insertions(+), 9 deletions(-) diff --git a/lib/main.js b/lib/main.js index 47200c70..4be73f59 100644 --- a/lib/main.js +++ b/lib/main.js @@ -27,9 +27,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; Object.defineProperty(exports, "__esModule", { value: true }); const core = __importStar(require("@actions/core")); const crypto = __importStar(require("crypto")); @@ -37,7 +34,6 @@ const exec = __importStar(require("@actions/exec")); const io = __importStar(require("@actions/io")); const actions_secret_parser_1 = require("actions-secret-parser"); const ServicePrincipalLogin_1 = require("./PowerShell/ServicePrincipalLogin"); -const Constants_1 = __importDefault(require("./PowerShell/Constants")); var azPath; var prefix = !!process.env.AZURE_HTTP_USER_AGENT ? `${process.env.AZURE_HTTP_USER_AGENT}` : ""; var azPSHostEnv = !!process.env.AZUREPS_HOST_ENVIRONMENT ? `${process.env.AZUREPS_HOST_ENVIRONMENT}` : ""; @@ -54,6 +50,7 @@ function main() { core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azurePSHostEnv); azPath = yield io.which("az", true); yield executeAzCliCommand("--version"); + let azureSupportedCloudName = ["azureusgovernment", "azurechinacloud", "azuregermancloud", "azurecloud", "azurestack"]; let creds = core.getInput('creds', { required: true }); let secrets = new actions_secret_parser_1.SecretParser(creds, actions_secret_parser_1.FormatType.JSON); let servicePrincipalId = secrets.getSecret("$.clientId", false); @@ -67,7 +64,7 @@ function main() { if (!servicePrincipalId || !servicePrincipalKey || !tenantId || !subscriptionId) { throw new Error("Not all values are present in the creds object. Ensure clientId, clientSecret, tenantId and subscriptionId are supplied."); } - if (!Constants_1.default.AzureSupportedCloudName.includes(environment)) { + if (!azureSupportedCloudName.includes(environment)) { throw new Error("Unsupported value for environment is passed.The list of supported values for environment are ‘azureusgovernment', ‘azurechinacloud’, ‘azuregermancloud’, ‘azurecloud’ or ’azurestack’"); } // Attempting Az cli login diff --git a/src/PowerShell/Constants.ts b/src/PowerShell/Constants.ts index 572b7b70..9613db1d 100644 --- a/src/PowerShell/Constants.ts +++ b/src/PowerShell/Constants.ts @@ -10,5 +10,4 @@ export default class Constants { static readonly Success: string = "Success"; static readonly Error: string = "Error"; static readonly AzVersion: string = "AzVersion"; - static readonly AzureSupportedCloudName:string[] = ["azureusgovernment", "azurechinacloud", "azuregermancloud","azurecloud","azurestack"]; } \ No newline at end of file diff --git a/src/main.ts b/src/main.ts index 8139be21..0fd469b9 100644 --- a/src/main.ts +++ b/src/main.ts @@ -4,7 +4,6 @@ import * as exec from '@actions/exec'; import * as io from '@actions/io'; import { FormatType, SecretParser } from 'actions-secret-parser'; import { ServicePrincipalLogin } from './PowerShell/ServicePrincipalLogin'; -import Constants from './PowerShell/Constants'; var azPath: string; var prefix = !!process.env.AZURE_HTTP_USER_AGENT ? `${process.env.AZURE_HTTP_USER_AGENT}` : ""; @@ -23,7 +22,8 @@ async function main() { azPath = await io.which("az", true); await executeAzCliCommand("--version"); - + + let azureSupportedCloudName:string[] = ["azureusgovernment", "azurechinacloud", "azuregermancloud","azurecloud","azurestack"]; let creds = core.getInput('creds', { required: true }); let secrets = new SecretParser(creds, FormatType.JSON); let servicePrincipalId = secrets.getSecret("$.clientId", false); @@ -34,11 +34,12 @@ async function main() { let environment = core.getInput("environment"); environment = environment.toLowerCase(); const enableAzPSSession = core.getInput('enable-AzPSSession').toLowerCase() === "true"; + if (!servicePrincipalId || !servicePrincipalKey || !tenantId || !subscriptionId) { throw new Error("Not all values are present in the creds object. Ensure clientId, clientSecret, tenantId and subscriptionId are supplied."); } - if(!Constants.AzureSupportedCloudName.includes(environment)){ + if(!azureSupportedCloudName.includes(environment)){ throw new Error("Unsupported value for environment is passed.The list of supported values for environment are ‘azureusgovernment', ‘azurechinacloud’, ‘azuregermancloud’, ‘azurecloud’ or ’azurestack’"); } From e22df6b974cadf9b70d6190368202c78502b5997 Mon Sep 17 00:00:00 2001 From: Zainuden Veetikadam Date: Tue, 8 Dec 2020 14:40:55 +0530 Subject: [PATCH 10/12] added library of Consts.js --- lib/PowerShell/Constants.js | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/PowerShell/Constants.js b/lib/PowerShell/Constants.js index 8ba2db80..98f75ccf 100644 --- a/lib/PowerShell/Constants.js +++ b/lib/PowerShell/Constants.js @@ -12,4 +12,3 @@ Constants.ServicePrincipal = "ServicePrincipal"; Constants.Success = "Success"; Constants.Error = "Error"; Constants.AzVersion = "AzVersion"; -Constants.AzureSupportedCloudName = ["azureusgovernment", "azurechinacloud", "azuregermancloud", "azurecloud", "azurestack"]; From ab062435f90bc91cec1849b0028452826abbb141 Mon Sep 17 00:00:00 2001 From: Zainuden Veetikadam Date: Tue, 8 Dec 2020 14:49:48 +0530 Subject: [PATCH 11/12] changes from arary to set --- lib/main.js | 4 ++-- src/main.ts | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/main.js b/lib/main.js index 4be73f59..bf4b8b03 100644 --- a/lib/main.js +++ b/lib/main.js @@ -50,7 +50,7 @@ function main() { core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azurePSHostEnv); azPath = yield io.which("az", true); yield executeAzCliCommand("--version"); - let azureSupportedCloudName = ["azureusgovernment", "azurechinacloud", "azuregermancloud", "azurecloud", "azurestack"]; + let azureSupportedCloudName = new Set(["azureusgovernment", "azurechinacloud", "azuregermancloud", "azurecloud", "azurestack"]); let creds = core.getInput('creds', { required: true }); let secrets = new actions_secret_parser_1.SecretParser(creds, actions_secret_parser_1.FormatType.JSON); let servicePrincipalId = secrets.getSecret("$.clientId", false); @@ -64,7 +64,7 @@ function main() { if (!servicePrincipalId || !servicePrincipalKey || !tenantId || !subscriptionId) { throw new Error("Not all values are present in the creds object. Ensure clientId, clientSecret, tenantId and subscriptionId are supplied."); } - if (!azureSupportedCloudName.includes(environment)) { + if (!azureSupportedCloudName.has(environment)) { throw new Error("Unsupported value for environment is passed.The list of supported values for environment are ‘azureusgovernment', ‘azurechinacloud’, ‘azuregermancloud’, ‘azurecloud’ or ’azurestack’"); } // Attempting Az cli login diff --git a/src/main.ts b/src/main.ts index 0fd469b9..e31e9854 100644 --- a/src/main.ts +++ b/src/main.ts @@ -23,7 +23,7 @@ async function main() { azPath = await io.which("az", true); await executeAzCliCommand("--version"); - let azureSupportedCloudName:string[] = ["azureusgovernment", "azurechinacloud", "azuregermancloud","azurecloud","azurestack"]; + let azureSupportedCloudName = new Set(["azureusgovernment", "azurechinacloud", "azuregermancloud","azurecloud","azurestack"]); let creds = core.getInput('creds', { required: true }); let secrets = new SecretParser(creds, FormatType.JSON); let servicePrincipalId = secrets.getSecret("$.clientId", false); @@ -39,7 +39,7 @@ async function main() { throw new Error("Not all values are present in the creds object. Ensure clientId, clientSecret, tenantId and subscriptionId are supplied."); } - if(!azureSupportedCloudName.includes(environment)){ + if(!azureSupportedCloudName.has(environment)){ throw new Error("Unsupported value for environment is passed.The list of supported values for environment are ‘azureusgovernment', ‘azurechinacloud’, ‘azuregermancloud’, ‘azurecloud’ or ’azurestack’"); } From 4610f2b768757d3e1510d1d2e284dcf7dc397a4f Mon Sep 17 00:00:00 2001 From: Zainuden Veetikadam Date: Tue, 8 Dec 2020 14:56:31 +0530 Subject: [PATCH 12/12] changes to environment input --- lib/main.js | 3 +-- src/main.ts | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/lib/main.js b/lib/main.js index bf4b8b03..e45d9265 100644 --- a/lib/main.js +++ b/lib/main.js @@ -58,8 +58,7 @@ function main() { let tenantId = secrets.getSecret("$.tenantId", false); let subscriptionId = secrets.getSecret("$.subscriptionId", false); let resourceManagerEndpointUrl = secrets.getSecret("$.resourceManagerEndpointUrl", false); - let environment = core.getInput("environment"); - environment = environment.toLowerCase(); + let environment = core.getInput("environment").toLowerCase(); const enableAzPSSession = core.getInput('enable-AzPSSession').toLowerCase() === "true"; if (!servicePrincipalId || !servicePrincipalKey || !tenantId || !subscriptionId) { throw new Error("Not all values are present in the creds object. Ensure clientId, clientSecret, tenantId and subscriptionId are supplied."); diff --git a/src/main.ts b/src/main.ts index e31e9854..a13d1453 100644 --- a/src/main.ts +++ b/src/main.ts @@ -31,8 +31,7 @@ async function main() { let tenantId = secrets.getSecret("$.tenantId", false); let subscriptionId = secrets.getSecret("$.subscriptionId", false); let resourceManagerEndpointUrl = secrets.getSecret("$.resourceManagerEndpointUrl", false); - let environment = core.getInput("environment"); - environment = environment.toLowerCase(); + let environment = core.getInput("environment").toLowerCase(); const enableAzPSSession = core.getInput('enable-AzPSSession').toLowerCase() === "true"; if (!servicePrincipalId || !servicePrincipalKey || !tenantId || !subscriptionId) {