mirror of
https://github.com/azure/login.git
synced 2026-03-12 18:07:08 -04:00
Adding federated token logs & optional audience parameter (#159)
* cherry pick changes * added audience field option in input params * added js * removed extra spaces * Adding logs to surface AZ-CLI and powershell errors (#171) * removing token logs
This commit is contained in:
@@ -121,7 +121,7 @@ jobs:
|
||||
az group list
|
||||
pwd
|
||||
```
|
||||
This action supports login az powershell as well for both windows and linux runners by setting an input parameter `enable-AzPSSession: true`. Below is the sample workflow for the same using the windows runner. Please note that powershell login is not supported in Macos runners.
|
||||
Users can also specify `audience` field for access-token in the input parameters of the action. If not specified, it is defaulted to `api://AzureADTokenExchange`. This action supports login az powershell as well for both windows and linux runners by setting an input parameter `enable-AzPSSession: true`. Below is the sample workflow for the same using the windows runner. Please note that powershell login is not supported in Macos runners.
|
||||
|
||||
## Sample workflow that uses Azure login action using OIDC to run az PowerShell (Windows)
|
||||
|
||||
|
||||
@@ -26,6 +26,10 @@ inputs:
|
||||
description: 'Set this value to true to enable support for accessing tenants without subscriptions'
|
||||
required: false
|
||||
default: false
|
||||
audience:
|
||||
description: 'Provide audience field for access-token. Default value is api://AzureADTokenExchange'
|
||||
required: false
|
||||
default: 'api://AzureADTokenExchange'
|
||||
branding:
|
||||
icon: 'login.svg'
|
||||
color: 'blue'
|
||||
|
||||
@@ -1,4 +1,23 @@
|
||||
"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) {
|
||||
@@ -8,17 +27,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
||||
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;
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ServicePrincipalLogin = void 0;
|
||||
const core = __importStar(require("@actions/core"));
|
||||
const Utils_1 = __importDefault(require("./Utilities/Utils"));
|
||||
const PowerShellToolRunner_1 = __importDefault(require("./Utilities/PowerShellToolRunner"));
|
||||
@@ -46,10 +59,18 @@ class ServicePrincipalLogin {
|
||||
login() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
let output = "";
|
||||
let commandStdErr = false;
|
||||
const options = {
|
||||
listeners: {
|
||||
stdout: (data) => {
|
||||
output += data.toString();
|
||||
},
|
||||
stderr: (data) => {
|
||||
let error = data.toString();
|
||||
if (error && error.trim().length !== 0) {
|
||||
commandStdErr = true;
|
||||
core.error(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,4 +1,23 @@
|
||||
"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) {
|
||||
@@ -8,13 +27,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
||||
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 io = __importStar(require("@actions/io"));
|
||||
const exec = __importStar(require("@actions/exec"));
|
||||
@@ -28,6 +40,7 @@ class PowerShellToolRunner {
|
||||
}
|
||||
static executePowerShellScriptBlock(scriptBlock, options = {}) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
//Options for error handling
|
||||
yield exec.exec(`"${PowerShellToolRunner.psPath}" -Command`, [scriptBlock], options);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,9 +1,21 @@
|
||||
"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 (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
|
||||
result["default"] = mod;
|
||||
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 __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
|
||||
@@ -1,4 +1,23 @@
|
||||
"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) {
|
||||
@@ -8,13 +27,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
||||
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;
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
|
||||
69
lib/main.js
69
lib/main.js
@@ -1,4 +1,23 @@
|
||||
"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) {
|
||||
@@ -8,13 +27,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
||||
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 exec = __importStar(require("@actions/exec"));
|
||||
@@ -27,6 +39,27 @@ var azPSHostEnv = !!process.env.AZUREPS_HOST_ENVIRONMENT ? `${process.env.AZUREP
|
||||
function main() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
try {
|
||||
//Options for error handling
|
||||
let commandStdErr = false;
|
||||
const loginOptions = {
|
||||
silent: true,
|
||||
ignoreReturnCode: true,
|
||||
failOnStdErr: true,
|
||||
listeners: {
|
||||
stderr: (data) => {
|
||||
let error = data.toString();
|
||||
//removing the keyword 'ERROR' to avoid duplicates while throwing error
|
||||
if (error.toLowerCase().startsWith('error')) {
|
||||
error = error.slice(5);
|
||||
}
|
||||
// printing error
|
||||
if (error && error.trim().length !== 0) {
|
||||
commandStdErr = true;
|
||||
core.error(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
// Set user agent variable
|
||||
var isAzCLISuccess = false;
|
||||
let usrAgentRepo = `${process.env.GITHUB_REPOSITORY}`;
|
||||
@@ -61,7 +94,6 @@ function main() {
|
||||
const allowNoSubscriptionsLogin = core.getInput('allow-no-subscriptions').toLowerCase() === "true";
|
||||
//Check for the credentials in individual parameters in the workflow.
|
||||
var servicePrincipalId = core.getInput('client-id', { required: false });
|
||||
;
|
||||
var servicePrincipalKey = null;
|
||||
var tenantId = core.getInput('tenant-id', { required: false });
|
||||
var subscriptionId = core.getInput('subscription-id', { required: false });
|
||||
@@ -72,7 +104,7 @@ function main() {
|
||||
if (servicePrincipalId || tenantId || subscriptionId) {
|
||||
//If few of the individual credentials (clent_id, tenat_id, subscription_id) are missing in action inputs.
|
||||
if (!(servicePrincipalId && tenantId && (subscriptionId || allowNoSubscriptionsLogin)))
|
||||
throw new Error("Few credentials are missing. ClientId,tenantId are mandatory. SubscriptionId is also mandatory if allow-no-subscriptions is not set.");
|
||||
throw new Error("Few credentials are missing. ClientId, tenantId are mandatory. SubscriptionId is also mandatory if allow-no-subscriptions is not set.");
|
||||
}
|
||||
else {
|
||||
if (creds) {
|
||||
@@ -103,7 +135,8 @@ function main() {
|
||||
if (enableOIDC) {
|
||||
console.log('Using OIDC authentication...');
|
||||
//generating ID-token
|
||||
federatedToken = yield core.getIDToken('api://AzureADTokenExchange');
|
||||
let audience = core.getInput('audience', { required: false });
|
||||
federatedToken = yield core.getIDToken(audience);
|
||||
if (!!federatedToken) {
|
||||
if (environment != "azurecloud")
|
||||
throw new Error(`Your current environment - "${environment}" is not supported for OIDC login.`);
|
||||
@@ -157,13 +190,13 @@ function main() {
|
||||
else {
|
||||
commonArgs = commonArgs.concat("-p", servicePrincipalKey);
|
||||
}
|
||||
yield executeAzCliCommand(`login`, true, {}, commonArgs);
|
||||
yield executeAzCliCommand(`login`, true, loginOptions, commonArgs);
|
||||
if (!allowNoSubscriptionsLogin) {
|
||||
var args = [
|
||||
"--subscription",
|
||||
subscriptionId
|
||||
];
|
||||
yield executeAzCliCommand(`account set`, true, {}, args);
|
||||
yield executeAzCliCommand(`account set`, true, loginOptions, args);
|
||||
}
|
||||
isAzCLISuccess = true;
|
||||
if (enableAzPSSession) {
|
||||
@@ -178,12 +211,11 @@ function main() {
|
||||
}
|
||||
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");
|
||||
core.setFailed("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(`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
|
||||
@@ -195,12 +227,7 @@ function main() {
|
||||
function executeAzCliCommand(command, silent, execOptions = {}, args = []) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
execOptions.silent = !!silent;
|
||||
try {
|
||||
yield exec.exec(`"${azPath}" ${command}`, args, execOptions);
|
||||
}
|
||||
catch (error) {
|
||||
throw new Error(error);
|
||||
}
|
||||
yield exec.exec(`"${azPath}" ${command}`, args, execOptions);
|
||||
});
|
||||
}
|
||||
main();
|
||||
|
||||
6943
package-lock.json
generated
6943
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "login",
|
||||
"version": "1.1.0",
|
||||
"version": "1.0.0",
|
||||
"description": "Login Azure wraps the az login, allowing for Azure actions to log into Azure",
|
||||
"main": "lib/main.js",
|
||||
"scripts": {
|
||||
@@ -21,6 +21,7 @@
|
||||
"@actions/core": "1.6.0",
|
||||
"@actions/exec": "^1.0.1",
|
||||
"@actions/io": "^1.0.1",
|
||||
"actions-secret-parser": "^1.0.2"
|
||||
"actions-secret-parser": "^1.0.2",
|
||||
"package-lock": "^1.0.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,10 +45,19 @@ export class ServicePrincipalLogin implements IAzurePowerShellSession {
|
||||
|
||||
async login() {
|
||||
let output: string = "";
|
||||
let commandStdErr = false;
|
||||
const options: any = {
|
||||
listeners: {
|
||||
stdout: (data: Buffer) => {
|
||||
output += data.toString();
|
||||
},
|
||||
stderr: (data: Buffer) => {
|
||||
let error = data.toString();
|
||||
if (error && error.trim().length !== 0)
|
||||
{
|
||||
commandStdErr = true;
|
||||
core.error(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -3,7 +3,6 @@ import * as exec from '@actions/exec';
|
||||
|
||||
export default class PowerShellToolRunner {
|
||||
static psPath: string;
|
||||
|
||||
static async init() {
|
||||
if(!PowerShellToolRunner.psPath) {
|
||||
PowerShellToolRunner.psPath = await io.which("pwsh", true);
|
||||
@@ -11,6 +10,7 @@ export default class PowerShellToolRunner {
|
||||
}
|
||||
|
||||
static async executePowerShellScriptBlock(scriptBlock: string, options: any = {}) {
|
||||
//Options for error handling
|
||||
await exec.exec(`"${PowerShellToolRunner.psPath}" -Command`, [scriptBlock], options)
|
||||
}
|
||||
}
|
||||
442
src/main.ts
442
src/main.ts
@@ -1,214 +1,230 @@
|
||||
import * as core from '@actions/core';
|
||||
import * as exec from '@actions/exec';
|
||||
import * as io from '@actions/io';
|
||||
import { FormatType, SecretParser } from 'actions-secret-parser';
|
||||
import { ServicePrincipalLogin } from './PowerShell/ServicePrincipalLogin';
|
||||
|
||||
var azPath: string;
|
||||
var prefix = !!process.env.AZURE_HTTP_USER_AGENT ? `${process.env.AZURE_HTTP_USER_AGENT}` : "";
|
||||
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 = `${process.env.GITHUB_REPOSITORY}`;
|
||||
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);
|
||||
core.debug(`az cli version used: ${azPath}`);
|
||||
let azureSupportedCloudName = new Set([
|
||||
"azureusgovernment",
|
||||
"azurechinacloud",
|
||||
"azuregermancloud",
|
||||
"azurecloud",
|
||||
"azurestack"]);
|
||||
|
||||
let output: string = "";
|
||||
const execOptions: any = {
|
||||
listeners: {
|
||||
stdout: (data: Buffer) => {
|
||||
output += data.toString();
|
||||
}
|
||||
}
|
||||
};
|
||||
await executeAzCliCommand("--version", true, execOptions);
|
||||
core.debug(`az cli version used:\n${output}`);
|
||||
|
||||
let creds = core.getInput('creds', { required: false });
|
||||
let secrets = creds ? new SecretParser(creds, FormatType.JSON) : null;
|
||||
let environment = core.getInput("environment").toLowerCase();
|
||||
const enableAzPSSession = core.getInput('enable-AzPSSession').toLowerCase() === "true";
|
||||
const allowNoSubscriptionsLogin = core.getInput('allow-no-subscriptions').toLowerCase() === "true";
|
||||
|
||||
//Check for the credentials in individual parameters in the workflow.
|
||||
var servicePrincipalId = core.getInput('client-id', { required: false });;
|
||||
var servicePrincipalKey = null;
|
||||
var tenantId = core.getInput('tenant-id', { required: false });
|
||||
var subscriptionId = core.getInput('subscription-id', { required: false });
|
||||
var resourceManagerEndpointUrl = "https://management.azure.com/";
|
||||
var enableOIDC = true;
|
||||
var federatedToken = null;
|
||||
|
||||
// If any of the individual credentials (clent_id, tenat_id, subscription_id) is present.
|
||||
if (servicePrincipalId || tenantId || subscriptionId) {
|
||||
|
||||
//If few of the individual credentials (clent_id, tenat_id, subscription_id) are missing in action inputs.
|
||||
if (!(servicePrincipalId && tenantId && (subscriptionId || allowNoSubscriptionsLogin)))
|
||||
throw new Error("Few credentials are missing. ClientId,tenantId are mandatory. SubscriptionId is also mandatory if allow-no-subscriptions is not set.");
|
||||
}
|
||||
else {
|
||||
if (creds) {
|
||||
core.debug('using creds JSON...');
|
||||
enableOIDC = false;
|
||||
servicePrincipalId = secrets.getSecret("$.clientId", true);
|
||||
servicePrincipalKey = secrets.getSecret("$.clientSecret", true);
|
||||
tenantId = secrets.getSecret("$.tenantId", true);
|
||||
subscriptionId = secrets.getSecret("$.subscriptionId", true);
|
||||
resourceManagerEndpointUrl = secrets.getSecret("$.resourceManagerEndpointUrl", false);
|
||||
}
|
||||
else {
|
||||
throw new Error("Credentials are not passed for Login action.");
|
||||
}
|
||||
}
|
||||
//generic checks
|
||||
//servicePrincipalKey is only required in non-oidc scenario.
|
||||
if (!servicePrincipalId || !tenantId || !(servicePrincipalKey || enableOIDC)) {
|
||||
throw new Error("Not all values are present in the credentials. Ensure clientId, clientSecret and tenantId are supplied.");
|
||||
}
|
||||
if (!subscriptionId && !allowNoSubscriptionsLogin) {
|
||||
throw new Error("Not all values are present in the credentials. Ensure subscriptionId is supplied.");
|
||||
}
|
||||
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’");
|
||||
}
|
||||
|
||||
// OIDC specific checks
|
||||
if (enableOIDC) {
|
||||
console.log('Using OIDC authentication...')
|
||||
//generating ID-token
|
||||
federatedToken = await core.getIDToken('api://AzureADTokenExchange');
|
||||
if (!!federatedToken) {
|
||||
if (environment != "azurecloud")
|
||||
throw new Error(`Your current environment - "${environment}" is not supported for OIDC login.`);
|
||||
}
|
||||
else {
|
||||
throw new Error("Could not get ID token for authentication.");
|
||||
}
|
||||
}
|
||||
|
||||
// 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}"`);
|
||||
|
||||
// Attempting Az cli login
|
||||
var commonArgs = ["--service-principal",
|
||||
"-u", servicePrincipalId,
|
||||
"--tenant", tenantId
|
||||
];
|
||||
if (allowNoSubscriptionsLogin) {
|
||||
commonArgs = commonArgs.concat("--allow-no-subscriptions");
|
||||
}
|
||||
if (enableOIDC) {
|
||||
commonArgs = commonArgs.concat("--federated-token", federatedToken);
|
||||
}
|
||||
else {
|
||||
commonArgs = commonArgs.concat("-p", servicePrincipalKey);
|
||||
}
|
||||
await executeAzCliCommand(`login`, true, {}, commonArgs);
|
||||
|
||||
if (!allowNoSubscriptionsLogin) {
|
||||
var args = [
|
||||
"--subscription",
|
||||
subscriptionId
|
||||
];
|
||||
await executeAzCliCommand(`account set`, true, {}, args);
|
||||
}
|
||||
isAzCLISuccess = true;
|
||||
if (enableAzPSSession) {
|
||||
// Attempting Az PS login
|
||||
console.log(`Running Azure PS Login`);
|
||||
var spnlogin: ServicePrincipalLogin;
|
||||
|
||||
spnlogin = new ServicePrincipalLogin(
|
||||
servicePrincipalId,
|
||||
servicePrincipalKey,
|
||||
federatedToken,
|
||||
tenantId,
|
||||
subscriptionId,
|
||||
allowNoSubscriptionsLogin,
|
||||
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,
|
||||
execOptions: any = {},
|
||||
args: any = []) {
|
||||
execOptions.silent = !!silent;
|
||||
try {
|
||||
await exec.exec(`"${azPath}" ${command}`, args, execOptions);
|
||||
}
|
||||
catch (error) {
|
||||
throw new Error(error);
|
||||
}
|
||||
}
|
||||
|
||||
import * as core from '@actions/core';
|
||||
import * as exec from '@actions/exec';
|
||||
import { ExecOptions } from '@actions/exec/lib/interfaces';
|
||||
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 {
|
||||
//Options for error handling
|
||||
let commandStdErr = false;
|
||||
const loginOptions: ExecOptions = {
|
||||
silent: true,
|
||||
ignoreReturnCode: true,
|
||||
failOnStdErr: true,
|
||||
listeners: {
|
||||
stderr: (data: Buffer) => {
|
||||
let error = data.toString();
|
||||
//removing the keyword 'ERROR' to avoid duplicates while throwing error
|
||||
if (error.toLowerCase().startsWith('error')) {
|
||||
error = error.slice(5);
|
||||
}
|
||||
// printing error
|
||||
if (error && error.trim().length !== 0) {
|
||||
commandStdErr = true;
|
||||
core.error(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Set user agent variable
|
||||
var isAzCLISuccess = false;
|
||||
let usrAgentRepo = `${process.env.GITHUB_REPOSITORY}`;
|
||||
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);
|
||||
core.debug(`az cli version used: ${azPath}`);
|
||||
let azureSupportedCloudName = new Set([
|
||||
"azureusgovernment",
|
||||
"azurechinacloud",
|
||||
"azuregermancloud",
|
||||
"azurecloud",
|
||||
"azurestack"]);
|
||||
|
||||
let output: string = "";
|
||||
const execOptions: any = {
|
||||
listeners: {
|
||||
stdout: (data: Buffer) => {
|
||||
output += data.toString();
|
||||
}
|
||||
}
|
||||
};
|
||||
await executeAzCliCommand("--version", true, execOptions);
|
||||
core.debug(`az cli version used:\n${output}`);
|
||||
|
||||
let creds = core.getInput('creds', { required: false });
|
||||
let secrets = creds ? new SecretParser(creds, FormatType.JSON) : null;
|
||||
let environment = core.getInput("environment").toLowerCase();
|
||||
const enableAzPSSession = core.getInput('enable-AzPSSession').toLowerCase() === "true";
|
||||
const allowNoSubscriptionsLogin = core.getInput('allow-no-subscriptions').toLowerCase() === "true";
|
||||
|
||||
//Check for the credentials in individual parameters in the workflow.
|
||||
var servicePrincipalId = core.getInput('client-id', { required: false });
|
||||
var servicePrincipalKey = null;
|
||||
var tenantId = core.getInput('tenant-id', { required: false });
|
||||
var subscriptionId = core.getInput('subscription-id', { required: false });
|
||||
var resourceManagerEndpointUrl = "https://management.azure.com/";
|
||||
var enableOIDC = true;
|
||||
var federatedToken = null;
|
||||
|
||||
// If any of the individual credentials (clent_id, tenat_id, subscription_id) is present.
|
||||
if (servicePrincipalId || tenantId || subscriptionId) {
|
||||
|
||||
//If few of the individual credentials (clent_id, tenat_id, subscription_id) are missing in action inputs.
|
||||
if (!(servicePrincipalId && tenantId && (subscriptionId || allowNoSubscriptionsLogin)))
|
||||
throw new Error("Few credentials are missing. ClientId, tenantId are mandatory. SubscriptionId is also mandatory if allow-no-subscriptions is not set.");
|
||||
}
|
||||
else {
|
||||
if (creds) {
|
||||
core.debug('using creds JSON...');
|
||||
enableOIDC = false;
|
||||
servicePrincipalId = secrets.getSecret("$.clientId", true);
|
||||
servicePrincipalKey = secrets.getSecret("$.clientSecret", true);
|
||||
tenantId = secrets.getSecret("$.tenantId", true);
|
||||
subscriptionId = secrets.getSecret("$.subscriptionId", true);
|
||||
resourceManagerEndpointUrl = secrets.getSecret("$.resourceManagerEndpointUrl", false);
|
||||
}
|
||||
else {
|
||||
throw new Error("Credentials are not passed for Login action.");
|
||||
}
|
||||
}
|
||||
//generic checks
|
||||
//servicePrincipalKey is only required in non-oidc scenario.
|
||||
if (!servicePrincipalId || !tenantId || !(servicePrincipalKey || enableOIDC)) {
|
||||
throw new Error("Not all values are present in the credentials. Ensure clientId, clientSecret and tenantId are supplied.");
|
||||
}
|
||||
if (!subscriptionId && !allowNoSubscriptionsLogin) {
|
||||
throw new Error("Not all values are present in the credentials. Ensure subscriptionId is supplied.");
|
||||
}
|
||||
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’");
|
||||
}
|
||||
|
||||
// OIDC specific checks
|
||||
if (enableOIDC) {
|
||||
console.log('Using OIDC authentication...')
|
||||
//generating ID-token
|
||||
let audience = core.getInput('audience', { required: false });
|
||||
federatedToken = await core.getIDToken(audience);
|
||||
if (!!federatedToken) {
|
||||
if (environment != "azurecloud")
|
||||
throw new Error(`Your current environment - "${environment}" is not supported for OIDC login.`);
|
||||
}
|
||||
else {
|
||||
throw new Error("Could not get ID token for authentication.");
|
||||
}
|
||||
}
|
||||
|
||||
// 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}"`);
|
||||
|
||||
// Attempting Az cli login
|
||||
var commonArgs = ["--service-principal",
|
||||
"-u", servicePrincipalId,
|
||||
"--tenant", tenantId
|
||||
];
|
||||
if (allowNoSubscriptionsLogin) {
|
||||
commonArgs = commonArgs.concat("--allow-no-subscriptions");
|
||||
}
|
||||
if (enableOIDC) {
|
||||
commonArgs = commonArgs.concat("--federated-token", federatedToken);
|
||||
}
|
||||
else {
|
||||
commonArgs = commonArgs.concat("-p", servicePrincipalKey);
|
||||
}
|
||||
await executeAzCliCommand(`login`, true, loginOptions, commonArgs);
|
||||
|
||||
if (!allowNoSubscriptionsLogin) {
|
||||
var args = [
|
||||
"--subscription",
|
||||
subscriptionId
|
||||
];
|
||||
await executeAzCliCommand(`account set`, true, loginOptions, args);
|
||||
}
|
||||
isAzCLISuccess = true;
|
||||
if (enableAzPSSession) {
|
||||
// Attempting Az PS login
|
||||
console.log(`Running Azure PS Login`);
|
||||
var spnlogin: ServicePrincipalLogin;
|
||||
|
||||
spnlogin = new ServicePrincipalLogin(
|
||||
servicePrincipalId,
|
||||
servicePrincipalKey,
|
||||
federatedToken,
|
||||
tenantId,
|
||||
subscriptionId,
|
||||
allowNoSubscriptionsLogin,
|
||||
environment,
|
||||
resourceManagerEndpointUrl);
|
||||
await spnlogin.initialize();
|
||||
await spnlogin.login();
|
||||
}
|
||||
|
||||
console.log("Login successful.");
|
||||
}
|
||||
catch (error) {
|
||||
if (!isAzCLISuccess) {
|
||||
core.setFailed("Az CLI Login failed. Please check the credentials. For more information refer https://aka.ms/create-secrets-for-GitHub-workflows");
|
||||
}
|
||||
else {
|
||||
core.setFailed(`Azure PowerShell Login failed. Please check the credentials. For more information refer https://aka.ms/create-secrets-for-GitHub-workflows"`);
|
||||
}
|
||||
}
|
||||
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,
|
||||
execOptions: any = {},
|
||||
args: any = []) {
|
||||
execOptions.silent = !!silent;
|
||||
await exec.exec(`"${azPath}" ${command}`, args, execOptions);
|
||||
}
|
||||
main();
|
||||
Reference in New Issue
Block a user