Compare commits

..

8 Commits

Author SHA1 Message Date
Kanika Pasrija
82829eb8b3 Update ServicePrinicipalLogin.test.ts 2021-10-22 16:16:01 +05:30
Balaga Gayatri
f7d7626e95 oidc changes 2021-10-22 13:25:18 +05:30
Sean MacKay
6bc1b5ecb9 Update Readme to improve examples for hand crafting credentials (#140)
The clientSecret is not a GUID, and this being labelled as such caused confusion when I tried to manually add a client secret and was met with a SecretId which was a GUID and a SecretValue which was not a GUID. Using the SecretId GUID from the Azure UI would not work.

Also, resourceManagerEndpointUrl was required but not shown in any examples. 

Finally, the value for it was hard to determine, as using several azure cli commands did not display it.

Co-authored-by: Kanika Pasrija <58769601+kanika1894@users.noreply.github.com>
2021-09-20 15:00:25 +05:30
Derek Seroky
f8979b3393 docs(README): update the Azure Gov cloud example (#134)
Updates the Azure Gov cloud example to have valid YAML syntax and to increase consistency between examples.

Co-authored-by: Kanika Pasrija <58769601+kanika1894@users.noreply.github.com>
2021-09-15 12:49:50 +05:30
Kanika Pasrija
7f56506e21 Adding repository parameter
This is to pick from forked branch
2021-09-15 12:39:33 +05:30
dependabot[bot]
0cf07a0171 Bump path-parse from 1.0.6 to 1.0.7 (#128)
Bumps [path-parse](https://github.com/jbgutierrez/path-parse) from 1.0.6 to 1.0.7.
- [Release notes](https://github.com/jbgutierrez/path-parse/releases)
- [Commits](https://github.com/jbgutierrez/path-parse/commits/v1.0.7)

---
updated-dependencies:
- dependency-name: path-parse
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Kanika Pasrija <58769601+kanika1894@users.noreply.github.com>
2021-09-13 17:04:06 +05:30
Balaga Gayatri
c9dca98403 Workflow for testing automation (#131)
* Create azure-login-pr-check.yml

* Update azure-login-pr-check.yml

* Update azure-login-pr-check.yml

* Update azure-login-pr-check.yml

* Update azure-login-pr-check.yml

* Update azure-login-pr-check.yml

* Update azure-login-pr-check.yml
2021-08-23 13:44:28 +05:30
Balaga Gayatri
177ab1c8df Rename bug-report---feature-request.md to bug-report-feature-request.md (#127) 2021-08-09 14:00:43 +05:30
12 changed files with 6494 additions and 120 deletions

View File

@@ -0,0 +1,72 @@
name: pr-check
on:
pull_request_target:
branches:
- master
- 'releases/*'
jobs:
az-login-test:
environment: Automation test
runs-on: windows-latest
steps:
- name: Checkout from PR branch
uses: actions/checkout@v2
with:
repository: ${{ github.event.pull_request.head.repo.full_name }}
ref: ${{ github.event.pull_request.head.ref }}
# Using 12.x version as an example
- name: Set Node.js 12.x for GitHub Action
uses: actions/setup-node@v1
with:
node-version: 12.x
- name: installing node_modules
run: npm install
- name: Build GitHub Action
run: npm run build
- name: 'Az CLI login with subscription'
uses: ./
with:
creds: ${{ secrets.AZURE_CREDENTIALS }}
- run: |
az account show
# az webapp list
- name: 'Az CLI login without subscription'
uses: ./
with:
creds: ${{ secrets.AZURE_CREDENTIALS_NO_SUB }}
allow-no-subscriptions: true
- run: |
az account show
- name: 'Azure PowerShell login with subscription'
uses: ./
with:
creds: ${{ secrets.AZURE_CREDENTIALS }}
enable-AzPSSession: true
- uses: azure/powershell@v1
with:
inlineScript: "Get-AzContext"
azPSVersion: "latest"
- name: 'Azure PowerShell login without subscription'
uses: ./
with:
creds: ${{secrets.AZURE_CREDENTIALS_NO_SUB}}
enable-AzPSSession: true
allow-no-subscriptions: true
- uses: azure/powershell@v1
with:
inlineScript: "Get-AzContext"
azPSVersion: "latest"

View File

@@ -78,19 +78,19 @@ jobs:
## Sample to connect to Azure US Government cloud
```
- name: Login to Azure US Gov Cloud with CLI
uses: azure/login@v1
with:
creds: ${{ secrets.AZURE_US_GOV_CREDENTIALS }}
environment: 'AzureUSGovernment'
enable-AzPSSession: false
- name: Login to Azure US Gov Cloud with Az Powershell
```yaml
- name: Login to Azure US Gov Cloud with CLI
uses: azure/login@v1
with:
creds: ${{ secrets.AZURE_US_GOV_CREDENTIALS }}
environment: 'AzureUSGovernment'
enable-AzPSSession: true
with:
creds: ${{ secrets.AZURE_US_GOV_CREDENTIALS }}
environment: 'AzureUSGovernment'
enable-AzPSSession: false
- name: Login to Azure US Gov Cloud with Az Powershell
uses: azure/login@v1
with:
creds: ${{ secrets.AZURE_US_GOV_CREDENTIALS }}
environment: 'AzureUSGovernment'
enable-AzPSSession: true
```
Refer to the [Azure PowerShell](https://github.com/azure/powershell) Github action to run your Azure PowerShell scripts.
@@ -171,7 +171,7 @@ The following steps describe how to create the service principal, assign the rol
```json
{
"clientId": "<GUID>",
"clientSecret": "<GUID>",
"clientSecret": "<CLIENT_SECRET_VALUE>",
"subscriptionId": "<GUID>",
"tenantId": "<GUID>",
(...)
@@ -183,7 +183,7 @@ The following steps describe how to create the service principal, assign the rol
NOTE: While adding secret `AZURE_CREDENTIALS` make sure to add like this
{"clientId": "<GUID>",
"clientSecret": "<GUID>",
"clientSecret": "<CLIENT_SECRET_VALUE>",
"subscriptionId": "<GUID>",
"tenantId": "<GUID>",
(...)}
@@ -192,7 +192,7 @@ NOTE: While adding secret `AZURE_CREDENTIALS` make sure to add like this
{
"clientId": "<GUID>",
"clientSecret": "<GUID>",
"clientSecret": "<CLIENT_SECRET_VALUE>",
"subscriptionId": "<GUID>",
"tenantId": "<GUID>",
(...)
@@ -212,6 +212,18 @@ However, a simple workaround for users who need this option can be:
creds: '{"clientId":"${{ secrets.CLIENT_ID }}","clientSecret":"${{ secrets.CLIENT_SECRET }}","subscriptionId":"${{ secrets.SUBSCRIPTION_ID }}","tenantId":"${{ secrets.TENANT_ID }}"}'
```
In a similar way, any additional parameter can be addded to creds such as resourceManagerEndpointUrl for Azure Stack, for example.
NOTE: If you want to hand craft your JSON object instead of using the output from the CLI command (for example, after using the UI to create the App Registration and Role assignment) the following fields are required:
```json
{
"clientId": "<GUID>",
"tenantId": "<GUID>",
"clientSecret": "<CLIENT_SECRET_VALUE>",
"subscriptionId": "<GUID>",
"resourceManagerEndpointUrl": "<URL>}
```
The resourceManagerEndpointUrl will be `https://management.azure.com/` if you are using the public azure cloud.
## Support for using `allow-no-subscriptions` flag with az login
Capability has been added to support access to tenants without subscriptions. This can be useful to run tenant level commands, such as `az ad`. The action accepts an optional parameter `allow-no-subscriptions` which is `false` by default.

View File

@@ -5,7 +5,7 @@ jest.mock('../../src/PowerShell/Utilities/PowerShellToolRunner');
let spnlogin: ServicePrincipalLogin;
beforeAll(() => {
spnlogin = new ServicePrincipalLogin("servicePrincipalID", "servicePrinicipalkey", "tenantId", "subscriptionId", false, null, null);
spnlogin = new ServicePrincipalLogin("servicePrincipalID", "servicePrinicipalkey", null, "tenantId", "subscriptionId", false, null, null);
});
afterEach(() => {

View File

@@ -4,7 +4,16 @@ description: 'AuthenticatetoAzureandrunyourAzCLIorAz
inputs:
creds:
description: 'Paste output of `az ad sp create-for-rbac` as value of secret variable: AZURE_CREDENTIALS'
required: true
required: false
client-id:
description: 'ClientId of the Azure Service principal created.'
required: false
tenant-id:
description: 'TenantId of the Azure Service principal created.'
required: false
subscription-id:
description: 'Azure subscriptionId'
required: false
enable-AzPSSession:
description: 'SetthisvaluetotruetoenableAzurePowerShellLogininadditiontoAzCLIlogin'
required: false
@@ -12,7 +21,7 @@ inputs:
environment:
description: 'Name of the environment. Supported values are azurecloud, azurestack, azureusgovernment, azurechinacloud, azuregermancloud. Default being azurecloud'
required: false
default: AzureCloud
default: azurecloud
allow-no-subscriptions:
description: 'Setthisvaluetotrueto enable support for accessing tenants without subscriptions'
required: false
@@ -22,4 +31,4 @@ branding:
color: 'blue'
runs:
using: 'node12'
main: 'lib/main.js'
main: 'lib/main.js'

View File

@@ -25,9 +25,10 @@ const PowerShellToolRunner_1 = __importDefault(require("./Utilities/PowerShellTo
const ScriptBuilder_1 = __importDefault(require("./Utilities/ScriptBuilder"));
const Constants_1 = __importDefault(require("./Constants"));
class ServicePrincipalLogin {
constructor(servicePrincipalId, servicePrincipalKey, tenantId, subscriptionId, allowNoSubscriptionsLogin, environment, resourceManagerEndpointUrl) {
constructor(servicePrincipalId, servicePrincipalKey, federatedToken, tenantId, subscriptionId, allowNoSubscriptionsLogin, environment, resourceManagerEndpointUrl) {
this.servicePrincipalId = servicePrincipalId;
this.servicePrincipalKey = servicePrincipalKey;
this.federatedToken = federatedToken;
this.tenantId = tenantId;
this.subscriptionId = subscriptionId;
this.environment = environment;
@@ -55,6 +56,7 @@ class ServicePrincipalLogin {
const args = {
servicePrincipalId: this.servicePrincipalId,
servicePrincipalKey: this.servicePrincipalKey,
federatedToken: this.federatedToken,
subscriptionId: this.subscriptionId,
environment: this.environment,
scopeLevel: ServicePrincipalLogin.scopeLevel,

View File

@@ -23,9 +23,17 @@ class ScriptBuilder {
if (args.environment.toLowerCase() == "azurestack") {
command += `Add-AzEnvironment -Name ${args.environment} -ARMEndpoint ${args.resourceManagerEndpointUrl} | out-null;`;
}
command += `Connect-AzAccount -ServicePrincipal -Tenant '${tenantId}' -Credential \
(New-Object System.Management.Automation.PSCredential('${args.servicePrincipalId}',(ConvertTo-SecureString '${args.servicePrincipalKey.replace("'", "''")}' -AsPlainText -Force))) \
-Environment '${args.environment}' | out-null;`;
// Separate command script for OIDC and non-OIDC
if (!!args.federatedToken) {
command += `Connect-AzAccount -ServicePrincipal -ApplicationId '${args.servicePrincipalId}' -Tenant '${tenantId}' -FederatedToken '${args.federatedToken}' \
-Environment '${args.environment}' | out-null;`;
}
else {
command += `Connect-AzAccount -ServicePrincipal -Tenant '${tenantId}' -Credential \
(New-Object System.Management.Automation.PSCredential('${args.servicePrincipalId}',(ConvertTo-SecureString '${args.servicePrincipalKey.replace("'", "''")}' -AsPlainText -Force))) \
-Environment '${args.environment}' | out-null;`;
}
// command to set the subscription
if (args.scopeLevel === Constants_1.default.Subscription && !args.allowNoSubscriptionsLogin) {
command += `Set-AzContext -SubscriptionId '${args.subscriptionId}' -TenantId '${tenantId}' | out-null;`;
}

View File

@@ -36,6 +36,7 @@ function main() {
core.exportVariable('AZURE_HTTP_USER_AGENT', userAgentString);
core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azurePSHostEnv);
azPath = yield io.which("az", true);
core.debug(`az cli version used: ${azPath}`);
let azureSupportedCloudName = new Set([
"azureusgovernment",
"azurechinacloud",
@@ -53,25 +54,64 @@ function main() {
};
yield executeAzCliCommand("--version", true, execOptions);
core.debug(`az cli version used:\n${output}`);
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 creds = core.getInput('creds', { required: false });
let secrets = creds ? new actions_secret_parser_1.SecretParser(creds, actions_secret_parser_1.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";
if (!servicePrincipalId || !servicePrincipalKey || !tenantId) {
throw new Error("Not all values are present in the creds object. Ensure clientId, clientSecret and tenantId are supplied.");
//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 creds object. Ensure subscriptionId is supplied.");
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 = yield 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) {
@@ -104,25 +144,22 @@ function main() {
yield 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) {
let args = [
"--allow-no-subscriptions",
"--service-principal",
"-u", servicePrincipalId,
"-p", servicePrincipalKey,
"--tenant", tenantId
];
yield executeAzCliCommand(`login`, true, {}, args);
commonArgs = commonArgs.concat("--allow-no-subscriptions");
}
if (enableOIDC) {
commonArgs = commonArgs.concat("--federated-token", federatedToken);
}
else {
let args = [
"--service-principal",
"-u", servicePrincipalId,
"-p", servicePrincipalKey,
"--tenant", tenantId
];
yield executeAzCliCommand(`login`, true, {}, args);
args = [
commonArgs = commonArgs.concat("-p", servicePrincipalKey);
}
yield executeAzCliCommand(`login`, true, {}, commonArgs);
if (!allowNoSubscriptionsLogin) {
var args = [
"--subscription",
subscriptionId
];
@@ -132,7 +169,8 @@ function main() {
if (enableAzPSSession) {
// Attempting Az PS login
console.log(`Running Azure PS Login`);
const spnlogin = new ServicePrincipalLogin_1.ServicePrincipalLogin(servicePrincipalId, servicePrincipalKey, tenantId, subscriptionId, allowNoSubscriptionsLogin, environment, resourceManagerEndpointUrl);
var spnlogin;
spnlogin = new ServicePrincipalLogin_1.ServicePrincipalLogin(servicePrincipalId, servicePrincipalKey, federatedToken, tenantId, subscriptionId, allowNoSubscriptionsLogin, environment, resourceManagerEndpointUrl);
yield spnlogin.initialize();
yield spnlogin.login();
}

6192
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -18,7 +18,7 @@
"typescript": "^3.6.3"
},
"dependencies": {
"@actions/core": "^1.2.6",
"@actions/core": "1.6.0",
"@actions/exec": "^1.0.1",
"@actions/io": "^1.0.1",
"actions-secret-parser": "^1.0.2"

View File

@@ -15,17 +15,20 @@ export class ServicePrincipalLogin implements IAzurePowerShellSession {
subscriptionId: string;
resourceManagerEndpointUrl: string;
allowNoSubscriptionsLogin: boolean;
federatedToken: string;
constructor(servicePrincipalId: string,
servicePrincipalKey: string,
tenantId: string,
constructor(servicePrincipalId: string,
servicePrincipalKey: string,
federatedToken: string,
tenantId: string,
subscriptionId: string,
allowNoSubscriptionsLogin: boolean,
environment: string,
resourceManagerEndpointUrl: string) {
this.servicePrincipalId = servicePrincipalId;
this.servicePrincipalKey = servicePrincipalKey;
this.federatedToken = federatedToken;
this.tenantId = tenantId;
this.subscriptionId = subscriptionId;
this.environment = environment;
@@ -52,6 +55,7 @@ export class ServicePrincipalLogin implements IAzurePowerShellSession {
const args: any = {
servicePrincipalId: this.servicePrincipalId,
servicePrincipalKey: this.servicePrincipalKey,
federatedToken: this.federatedToken,
subscriptionId: this.subscriptionId,
environment: this.environment,
scopeLevel: ServicePrincipalLogin.scopeLevel,

View File

@@ -8,17 +8,28 @@ export default class ScriptBuilder {
getAzPSLoginScript(scheme: string, tenantId: string, args: any): string {
let command = `Clear-AzContext -Scope Process;
Clear-AzContext -Scope CurrentUser -Force -ErrorAction SilentlyContinue;`;
if (scheme === Constants.ServicePrincipal) {
if (args.environment.toLowerCase() == "azurestack") {
command += `Add-AzEnvironment -Name ${args.environment} -ARMEndpoint ${args.resourceManagerEndpointUrl} | out-null;`;
}
command += `Connect-AzAccount -ServicePrincipal -Tenant '${tenantId}' -Credential \
(New-Object System.Management.Automation.PSCredential('${args.servicePrincipalId}',(ConvertTo-SecureString '${args.servicePrincipalKey.replace("'", "''")}' -AsPlainText -Force))) \
-Environment '${args.environment}' | out-null;`;
// Separate command script for OIDC and non-OIDC
if (!!args.federatedToken) {
command += `Connect-AzAccount -ServicePrincipal -ApplicationId '${args.servicePrincipalId}' -Tenant '${tenantId}' -FederatedToken '${args.federatedToken}' \
-Environment '${args.environment}' | out-null;`;
}
else {
command += `Connect-AzAccount -ServicePrincipal -Tenant '${tenantId}' -Credential \
(New-Object System.Management.Automation.PSCredential('${args.servicePrincipalId}',(ConvertTo-SecureString '${args.servicePrincipalKey.replace("'", "''")}' -AsPlainText -Force))) \
-Environment '${args.environment}' | out-null;`;
}
// command to set the subscription
if (args.scopeLevel === Constants.Subscription && !args.allowNoSubscriptionsLogin) {
command += `Set-AzContext -SubscriptionId '${args.subscriptionId}' -TenantId '${tenantId}' | out-null;`;
}
}
this.script += `try {
$ErrorActionPreference = "Stop"
$WarningPreference = "SilentlyContinue"
@@ -30,6 +41,7 @@ export default class ScriptBuilder {
$output['${Constants.Error}'] = $_.exception.Message
}
return ConvertTo-Json $output`;
core.debug(`Azure PowerShell Login Script: ${this.script}`);
return this.script;
}
@@ -51,4 +63,5 @@ export default class ScriptBuilder {
core.debug(`GetLatestModuleScript: ${this.script}`);
return this.script;
}
}
}

View File

@@ -20,10 +20,10 @@ async function main() {
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",
"azureusgovernment",
"azurechinacloud",
"azuregermancloud",
"azurecloud",
"azurestack"]);
@@ -38,30 +38,69 @@ async function main() {
};
await executeAzCliCommand("--version", true, execOptions);
core.debug(`az cli version used:\n${output}`);
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 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";
if (!servicePrincipalId || !servicePrincipalKey || !tenantId) {
throw new Error("Not all values are present in the creds object. Ensure clientId, clientSecret and tenantId are supplied.");
//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");
}
if (!subscriptionId && !allowNoSubscriptionsLogin) {
throw new Error("Not all values are present in the creds object. Ensure subscriptionId is supplied.");
// 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.");
}
}
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
if (environment == "azurestack") {
if (!resourceManagerEndpointUrl) {
@@ -81,71 +120,71 @@ async function main() {
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
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 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) {
let args = [
"--allow-no-subscriptions",
"--service-principal",
"-u", servicePrincipalId,
"-p", servicePrincipalKey,
"--tenant", tenantId
];
await executeAzCliCommand(`login`, true, {}, args);
commonArgs = commonArgs.concat("--allow-no-subscriptions");
}
if (enableOIDC) {
commonArgs = commonArgs.concat("--federated-token", federatedToken);
}
else {
let args = [
"--service-principal",
"-u", servicePrincipalId,
"-p", servicePrincipalKey,
"--tenant", tenantId
];
await executeAzCliCommand(`login`, true, {}, args);
args = [
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`);
const spnlogin: ServicePrincipalLogin = new ServicePrincipalLogin(
servicePrincipalId,
servicePrincipalKey,
tenantId,
subscriptionId,
var spnlogin: ServicePrincipalLogin;
spnlogin = new ServicePrincipalLogin(
servicePrincipalId,
servicePrincipalKey,
federatedToken,
tenantId,
subscriptionId,
allowNoSubscriptionsLogin,
environment,
environment,
resourceManagerEndpointUrl);
await spnlogin.initialize();
await spnlogin.login();
}
console.log("Login successful.");
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"`);
}
@@ -159,14 +198,13 @@ async function main() {
}
async function executeAzCliCommand(
command: string,
silent?: boolean,
execOptions: any = {},
command: string,
silent?: boolean,
execOptions: any = {},
args: any = []) {
execOptions.silent = !!silent;
try {
await exec.exec(`"${azPath}" ${command}`, args, execOptions);
await exec.exec(`"${azPath}" ${command}`, args, execOptions);
}
catch (error) {
throw new Error(error);