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