Compare commits

..

16 Commits

Author SHA1 Message Date
Balaga Gayatri
ca49e5ac91 Update main.js 2022-01-18 22:55:47 +05:30
Balaga Gayatri
5142ef661a Update main.ts 2022-01-18 22:54:28 +05:30
Balaga Gayatri
db989b3060 Delete .DS_Store 2021-12-16 21:51:49 +05:30
Dhiwakar Kusuma
276f50e2dc Update README.md (#189)
Updated Readme.md with App Registration instructions. Without the instructions new user will be lost with the instructions provided as none of the menus/options appear.
2021-12-13 23:14:29 +05:30
Balaga Gayatri
25454e5e2d printing token logs (#185) 2021-12-07 00:16:39 +05:30
Balaga Gayatri
0dd02392d7 Update README.md 2021-11-29 13:48:09 +05:30
Balaga Gayatri
aa88e1ccbd Update README.md 2021-11-29 12:35:23 +05:30
Balaga Gayatri
c8bf401503 Update README.md 2021-11-19 19:22:51 +05:30
Balaga Gayatri
37a47ac753 Update README.md (#173) 2021-11-17 12:48:23 +05:30
Balaga Gayatri
298eef0366 Updating samples and readme links (#172) 2021-11-15 17:27:52 +05:30
Balaga Gayatri
4799d94391 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
2021-11-15 12:45:07 +05:30
Balaga Gayatri
bd43696425 Update README.md 2021-11-12 13:09:38 +05:30
Balaga Gayatri
3e6f6e7d1b Update README.md 2021-10-22 18:46:47 +05:30
Balaga Gayatri
38942de1a5 Update README.md 2021-10-22 18:42:53 +05:30
Balaga Gayatri
151a993723 Update README.md 2021-10-22 16:41:44 +05:30
Balaga Gayatri
fd4c9019e3 oidc changes for master (#158)
* oidc changes

* Update ServicePrinicipalLogin.test.ts

Co-authored-by: Kanika Pasrija <58769601+kanika1894@users.noreply.github.com>
2021-10-22 16:27:01 +05:30
12 changed files with 4195 additions and 3697 deletions

294
README.md
View File

@@ -2,27 +2,36 @@
## Automate your GitHub workflows using Azure Actions ## Automate your GitHub workflows using Azure Actions
[GitHub Actions](https://help.github.com/en/articles/about-github-actions) gives you the flexibility to build an automated software development lifecycle workflow. [GitHub Actions](https://help.github.com/en/articles/about-github-actions) gives you the flexibility to build an automated software development lifecycle workflow.
With [GitHub Actions for Azure](https://github.com/Azure/actions/) you can create workflows that you can set up in your repository to build, test, package, release and **deploy** to Azure. With [GitHub Actions for Azure](https://github.com/Azure/actions/) you can create workflows that you can set up in your repository to build, test, package, release and **deploy** to Azure.
NOTE: you must have write permissions to the repository in question. If you're using a sample repository from Microsoft, be sure to first fork the repository to your own GitHub account.
Get started today with a [free Azure account](https://azure.com/free/open-source).
# GitHub Action for Azure Login # GitHub Action for Azure Login
With the Azure login Action, you can automate your workflow to do an Azure login using [Azure service principal](https://docs.microsoft.com/azure/active-directory/develop/app-objects-and-service-principals) and run Azure CLI and Azure PowerShell scripts. You can leverage this action for the public or soverign clouds including Azure Government and Azure Stack Hub (using the `environment` parameter). With the [Azure Login](https://github.com/Azure/login/blob/master/action.yml) Action, you can automate your workflow to do an Azure login using [Azure service principal](https://docs.microsoft.com/en-us/azure/active-directory/develop/app-objects-and-service-principals) and run Az CLI and Azure PowerShell scripts.
By default, the action only logs in with the Azure CLI (using the `az login` command). To log in with the Az PowerShell module, set `enable-AzPSSession` to true. To login to Azure tenants without any subscriptions, set the optional parameter `allow-no-subscriptions` to true. - By default, the action only logs in with the Azure CLI (using the `az login` command). To log in with the Az PowerShell module, set `enable-AzPSSession` to true. To login to Azure tenants without any subscriptions, set the optional parameter `allow-no-subscriptions` to true.
To login into one of the Azure Government clouds, set the optional parameter environment with supported cloud names AzureUSGovernment or AzureChinaCloud. If this parameter is not specified, it takes the default value AzureCloud and connect to the Azure Public Cloud. Additionally the parameter creds takes the Azure service principal created in the particular cloud to connect (Refer to Configure deployment credentials section below for details). - To login into one of the Azure Government clouds or Azure Stack, set the optional parameter `environment` with one of the supported values `AzureUSGovernment` or `AzureChinaCloud` or `AzureStack`. If this parameter is not specified, it takes the default value `AzureCloud` and connects to the Azure Public Cloud. Additionally the parameter `creds` takes the Azure service principal created in the particular cloud to connect (Refer to [this](#configure-a-service-principal-with-a-secret) section below for details).
- The Action supports two different ways of authentication with Azure. One using the Azure Service Principal with secrets. The other is OpenID connect (OIDC) method of authentication using Azure Service Principal with a Federated Identity Credential.
- To login using Azure Service Principal with a secret, follow [this](#configure-a-service-principal-with-a-secret) guidance.
- To login using **OpenID Connect (OIDC) based Federated Identity Credentials**,
1. Follow [this](#configure-a-service-principal-with-a-federated-credential-to-use-oidc-based-authentication) guidance to create a Federated Credential associated with your AD App (Service Principal). This is needed to establish OIDC trust between GitHub deployment workflows and the specific Azure resources scoped by the service principal.
2. In your GitHub workflow, Set `permissions:` with `id-token: write` at workflow level or job level based on whether the OIDC token needs to be auto-generated for all Jobs or a specific Job.
3. Within the Job deploying to Azure, add Azure/login action and pass the `client-id`, `tenant-id` and `subscription-id` of the Azure service principal associated with an OIDC Federated Identity Credential credeted in step (i)
Note:
- Ensure the CLI version is 2.30 or above to use OIDC support.
- OIDC support in Azure is in Public Preview and is supported only for public clouds. Support for other clouds like Government clouds, Azure Stacks would be added soon.
- GitHub runners will soon be updating the with the Az CLI and PowerShell versions that support with OIDC. Hence the below sample workflows include explicit instructions to download the same during workflow execution.
- By default, Azure access tokens issued during OIDC based login could have limited validity. This expiration time is configurable in Azure.
This repository contains GitHub Action for [Azure Login](https://github.com/Azure/login/blob/master/action.yml).
## Sample workflow that uses Azure login action to run az cli ## Sample workflow that uses Azure login action to run az cli
```yaml ```yaml
# File: .github/workflows/workflow.yml # File: .github/workflows/workflow.yml
on: [push] on: [push]
@@ -34,47 +43,106 @@ jobs:
build-and-deploy: build-and-deploy:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: azure/login@v1 - uses: azure/login@v1
with: with:
creds: ${{ secrets.AZURE_CREDENTIALS }} creds: ${{ secrets.AZURE_CREDENTIALS }}
- run: | - run: |
az webapp list --query "[?state=='Running']" az webapp list --query "[?state=='Running']"
``` ```
## Sample workflow that uses Azure login action to run Azure PowerShell ## Sample workflow that uses Azure login action to run Azure PowerShell
```yaml ```yaml
# File: .github/workflows/workflow.yml # File: .github/workflows/workflow.yml
on: [push] on: [push]
name: AzurePowerShellSample name: AzurePowerShellLoginSample
jobs: jobs:
build-and-deploy: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Login via Az module - name: Login via Az module
uses: azure/login@v1 uses: azure/login@v1
with: with:
creds: ${{secrets.AZURE_CREDENTIALS}} creds: ${{secrets.AZURE_CREDENTIALS}}
enable-AzPSSession: true enable-AzPSSession: true
- name: Run Az CLI script - run: |
run: | Get-AzVM -ResourceGroupName "ResourceGroup11"
az webapp list --query "[?state=='Running']"
- name: Run Azure PowerShell script
uses: azure/powershell@v1
with:
azPSVersion: '3.1.0'
inlineScript: |
Get-AzVM -ResourceGroupName "ActionsDemo"
``` ```
## Sample workflow that uses Azure login action using OIDC to run az cli (Linux)
```yaml
# File: .github/workflows/OIDC_workflow.yml
name: Run Azure Login with OIDC
on: [push]
permissions:
id-token: write
contents: read
jobs:
build-and-deploy:
runs-on: ubuntu-latest
steps:
- name: 'Az CLI login'
uses: azure/login@v1
with:
client-id: ${{ secrets.AZURE_CLIENT_ID }}
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
- name: 'Run az commands'
run: |
az account show
az group list
pwd
```
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)
```yaml
# File: .github/workflows/OIDC_workflow.yml
name: Run Azure Login with OIDC
on: [push]
permissions:
id-token: write
contents: read
jobs:
Windows-latest:
runs-on: windows-latest
steps:
- name: OIDC Login to Azure Public Cloud with AzPowershell (enableAzPSSession true)
uses: azure/login@v1
with:
client-id: ${{ secrets.AZURE_CLIENT_ID }}
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
enable-AzPSSession: true
- name: 'Get RG with powershell action'
uses: azure/powershell@v1
with:
inlineScript: |
Get-AzResourceGroup
azPSVersion: "latest"
```
Refer [Azure PowerShell](https://github.com/azure/powershell) Github action to run your Azure PowerShell scripts.
## Sample to connect to Azure US Government cloud ## Sample to connect to Azure US Government cloud
@@ -122,111 +190,80 @@ jobs:
Refer to the [Azure Stack Hub Login Action Tutorial](https://docs.microsoft.com/en-us/azure-stack/user/ci-cd-github-action-login-cli?view=azs-2008) for more detailed instructions. Refer to the [Azure Stack Hub Login Action Tutorial](https://docs.microsoft.com/en-us/azure-stack/user/ci-cd-github-action-login-cli?view=azs-2008) for more detailed instructions.
## Configure deployment credentials: ## Configure deployment credentials:
### Configure a service principal with a secret:
The previous sample workflows depend on a [secrets](https://docs.github.com/en/free-pro-team@latest/actions/reference/encrypted-secrets) named `AZURE_CREDENTIALS` in your repository. The value of this secret is expected to be a JSON object that represents a service principal (an identifer for an application or process) that authenticates the workflow with Azure. For using any credentials like Azure Service Principal, Publish Profile etc add them as [secrets](https://help.github.com/en/articles/virtual-environments-for-github-actions#creating-and-using-secrets-encrypted-variables) in the GitHub repository and then use them in the workflow.
To function correctly, this service principal must be assigned the [Contributor]((https://docs.microsoft.com/azure/role-based-access-control/built-in-roles#contributor)) role for the web app or the resource group that contains the web app.
The following steps describe how to create the service principal, assign the role, and create a secret in your repository with the resulting credentials. Follow the steps to configure Azure Service Principal with a secret:
* Define a new secret under your repository settings, Add secret menu
* Store the output of the below [az cli](https://docs.microsoft.com/en-us/cli/azure/?view=azure-cli-latest) command as the value of secret variable, for example 'AZURE_CREDENTIALS'
```bash
1. Open the Azure Cloud Shell at [https://shell.azure.com](https://shell.azure.com). You can alternately use the [Azure CLI](https://docs.microsoft.com/cli/azure/install-azure-cli?view=azure-cli-latest) if you've installed it locally. (For more information on Cloud Shell, see the [Cloud Shell Overview](https://docs.microsoft.com/azure/cloud-shell/overview).) az ad sp create-for-rbac --name "myApp" --role contributor \
--scopes /subscriptions/{subscription-id}/resourceGroups/{resource-group} \
--sdk-auth
# Replace {subscription-id}, {resource-group} with the subscription, resource group details
1.1 **(Required ONLY when environment is Azure Stack Hub)** Run the following command to set the SQL Management endpoint to 'not supported' # The command should output a JSON object similar to this:
```bash
az cloud update -n {environmentName} --endpoint-sql-management https://notsupported {
"clientId": "<GUID>",
``` "clientSecret": "<GUID>",
"subscriptionId": "<GUID>",
2. Use the [az ad sp create-for-rbac](https://docs.microsoft.com/cli/azure/ad/sp?view=azure-cli-latest#az_ad_sp_create_for_rbac) command to create a service principal and assign a Contributor role: "tenantId": "<GUID>",
(...)
For web apps (also more secure) }
```azurecli
az ad sp create-for-rbac --name "{sp-name}" --sdk-auth --role contributor \
--scopes /subscriptions/{subscription-id}/resourceGroups/{resource-group}/providers/Microsoft.Web/sites/{app-name}
```
For usage with other Azure services (Storage Accounts, Active Directory, etc.)
```azurecli
az ad sp create-for-rbac --name "{sp-name}" --sdk-auth --role contributor \
--scopes /subscriptions/{subscription-id}/resourceGroups/{resource-group}
```
Replace the following:
* `{sp-name}` with a suitable name for your service principal, such as the name of the app itself. The name must be unique within your organization.
* `{subscription-id}` with the subscription ID you want to use (found in Subscriptions in portal)
* `{resource-group}` the resource group containing the web app.
* [optional] `{app-name}` if you wish to have a tighter & more secure scope, use the first option and replace this with the name of the web app.
More info can be found [here](https://docs.microsoft.com/en-us/cli/azure/ad/sp?view=azure-cli-latest#az_ad_sp_create_for_rbac).
This command invokes Azure Active Directory (via the `ad` part of the command) to create a service principal (via `sp`) specifically for [Role-Based Access Control (RBAC)](https://docs.microsoft.com/azure/role-based-access-control/overview) (via `create-for-rbac`).
The `--role` argument specifies the permissions to grant to the service principal at the specified `--scope`. In this case, you grant the built-in [Contributor](https://docs.microsoft.com/azure/role-based-access-control/built-in-roles#contributor) role at the scope of the web app in the specified resource group in the specified subscription. If desired, you can omit the part of the scope starting with `/providers/...` to grant the service principal the Contributor role for the entire resource group. For security purposes, however, it's always preferable to grant permissions at the most restrictive scope possible.
3. When complete, the `az ad sp create-for-rbac` command displays JSON output in the following form (which is specified by the `--sdk-auth` argument):
```json
{
"clientId": "<GUID>",
"clientSecret": "<CLIENT_SECRET_VALUE>",
"subscriptionId": "<GUID>",
"tenantId": "<GUID>",
(...)
}
```
4. In your repository, use **Add secret** to create a new secret named `AZURE_CREDENTIALS` (as shown in the example workflow), or using whatever name is in your workflow file.
NOTE: While adding secret `AZURE_CREDENTIALS` make sure to add like this
{"clientId": "<GUID>",
"clientSecret": "<CLIENT_SECRET_VALUE>",
"subscriptionId": "<GUID>",
"tenantId": "<GUID>",
(...)}
instead of
{
"clientId": "<GUID>",
"clientSecret": "<CLIENT_SECRET_VALUE>",
"subscriptionId": "<GUID>",
"tenantId": "<GUID>",
(...)
}
to prevent unnecessary masking of `{ } ` in your logs which are in dictionary form.
5. Paste the entire JSON object produced by the `az ad sp create-for-rbac` command as the secret value and save the secret.
NOTE: to manage service principals created with `az ad sp create-for-rbac`, visit the [Azure portal](https://portal.azure.com), navigate to your Azure Active Directory, then select **Manage** > **App registrations** on the left-hand menu. Your service principal should appear in the list. Select a principal to navigate to its properties. You can also manage role assignments using the [az role assignment](https://docs.microsoft.com/cli/azure/role/assignment?view=azure-cli-latest) command.
NOTE: Currently there is no support for passing in the Subscription ID, Tenant ID, Client ID, and Client Secret as individual parameters instead of bundled in a single JSON object (creds).
However, a simple workaround for users who need this option can be:
```yaml
- uses: Azure/login@v1.1
with:
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. * Now in the workflow file in your branch: `.github/workflows/workflow.yml` replace the secret in Azure login action with your secret (Refer to the example above)
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: ### Configure a service principal with a Federated Credential to use OIDC based authentication:
```json
{
"clientId": "<GUID>", You can add federated credentials in the Azure portal or with the Microsoft Graph REST API.
"tenantId": "<GUID>",
"clientSecret": "<CLIENT_SECRET_VALUE>", #### Azure portal
"subscriptionId": "<GUID>", 1. [Register an application](https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app) in Azure Portal
"resourceManagerEndpointUrl": "<URL>} 2. Within the registered application, Go to **Certificates & secrets**.
``` 3. In the **Federated credentials** tab, select **Add credential**.
The resourceManagerEndpointUrl will be `https://management.azure.com/` if you are using the public azure cloud. 4. The **Add a credential** blade opens.
5. In the **Federated credential scenario** box select **GitHub actions deploying Azure resources**.
6. Specify the **Organization** and **Repository** for your GitHub Actions workflow which needs to access the Azure resources scoped by this App (Service Principal)
7. For **Entity type**, select **Environment**, **Branch**, **Pull request**, or **Tag** and specify the value, based on how you have configured the trigger for your GitHub workflow. For a more detailed overview, see [GitHub OIDC guidance]( https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/about-security-hardening-with-openid-connect#defining-[…]dc-claims).
8. Add a **Name** for the federated credential.
9. Click **Add** to configure the federated credential.
For a more detailed overview, see more guidance around [Azure Federated Credentials](https://docs.microsoft.com/en-us/azure/active-directory/develop/workload-identity-federation-create-trust-github).
#### Microsoft Graph
1. Launch [Azure Cloud Shell](https://portal.azure.com/#cloudshell/) and sign in to your tenant.
1. Create a federated identity credential
Run the following command to [create a new federated identity credential](https://docs.microsoft.com/en-us/graph/api/application-post-federatedidentitycredentials?view=graph-rest-beta&preserve-view=true) on your app (specified by the object ID of the app). Substitute the values `APPLICATION-OBJECT-ID`, `CREDENTIAL-NAME`, `SUBJECT`. The options for subject refer to your request filter. These are the conditions that OpenID Connect uses to determine when to issue an authentication token.
* specific environment
```azurecli
az rest --method POST --uri 'https://graph.microsoft.com/beta/applications/<APPLICATION-OBJECT-ID>/federatedIdentityCredentials' --body '{"name":"<CREDENTIAL-NAME>","issuer":"https://token.actions.githubusercontent.com","subject":"repo:octo-org/octo-repo:environment:Production","description":"Testing","audiences":["api://AzureADTokenExchange"]}'
```
* pull_request events
```azurecli
az rest --method POST --uri 'https://graph.microsoft.com/beta/applications/<APPLICATION-OBJECT-ID>/federatedIdentityCredentials' --body '{"name":"<CREDENTIAL-NAME>","issuer":"https://token.actions.githubusercontent.com","subject":"repo:octo-org/octo-repo:pull_request","description":"Testing","audiences":["api://AzureADTokenExchange"]}'
```
* specific branch
```azurecli
az rest --method POST --uri 'https://graph.microsoft.com/beta/applications/<APPLICATION-OBJECT-ID>/federatedIdentityCredentials' --body '{"name":"<CREDENTIAL-NAME>","issuer":"https://token.actions.githubusercontent.com","subject":"repo:octo-org/octo-repo:ref:refs/heads/{Branch}","description":"Testing","audiences":["api://AzureADTokenExchange"]}'
```
* specific tag
```azurecli
az rest --method POST --uri 'https://graph.microsoft.com/beta/applications/<APPLICATION-OBJECT-ID>/federatedIdentityCredentials' --body '{"name":"<CREDENTIAL-NAME>","issuer":"https://token.actions.githubusercontent.com","subject":"repo:octo-org/octo-repo:ref:refs/heads/{Tag}","description":"Testing","audiences":["api://AzureADTokenExchange"]}'
```
## Support for using `allow-no-subscriptions` flag with az login ## 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. Capability has been added to support access to tenants without subscriptions for both OIDC and non-OIDC. 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.
```yaml ```yaml
# File: .github/workflows/workflow.yml # File: .github/workflows/workflow.yml
@@ -259,12 +296,17 @@ This action doesn't implement ```az logout``` by default at the end of execution
az cache purge az cache purge
az account clear az account clear
``` ```
# Contributing # Contributing
This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com. This project welcomes contributions and suggestions. Most contributions require you to agree to a
Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us
the rights to use your contribution. For details, visit https://cla.opensource.microsoft.com.
For detailed developer guidelines, visit [developer guidelines for azure actions](https://github.com/Azure/actions/blob/main/docs/developer-guildelines.md). When you submit a pull request, a CLA bot will automatically determine whether you need to provide
a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions
provided by the bot. You will only need to do this once across all repos using our CLA.
When you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA. This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.

View File

@@ -26,6 +26,10 @@ inputs:
description: 'Setthisvaluetotrueto enable support for accessing tenants without subscriptions' description: 'Setthisvaluetotrueto enable support for accessing tenants without subscriptions'
required: false required: false
default: false default: false
audience:
description: 'Provide audience field for access-token. Default value is api://AzureADTokenExchange'
required: false
default: 'api://AzureADTokenExchange'
branding: branding:
icon: 'login.svg' icon: 'login.svg'
color: 'blue' color: 'blue'

View File

@@ -1,4 +1,23 @@
"use strict"; "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) { var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) { 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()); 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) { var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod }; return (mod && mod.__esModule) ? mod : { "default": mod };
}; };
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.ServicePrincipalLogin = void 0;
const core = __importStar(require("@actions/core")); const core = __importStar(require("@actions/core"));
const Utils_1 = __importDefault(require("./Utilities/Utils")); const Utils_1 = __importDefault(require("./Utilities/Utils"));
const PowerShellToolRunner_1 = __importDefault(require("./Utilities/PowerShellToolRunner")); const PowerShellToolRunner_1 = __importDefault(require("./Utilities/PowerShellToolRunner"));
@@ -46,10 +59,18 @@ class ServicePrincipalLogin {
login() { login() {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
let output = ""; let output = "";
let commandStdErr = false;
const options = { const options = {
listeners: { listeners: {
stdout: (data) => { stdout: (data) => {
output += data.toString(); output += data.toString();
},
stderr: (data) => {
let error = data.toString();
if (error && error.trim().length !== 0) {
commandStdErr = true;
core.error(error);
}
} }
} }
}; };

View File

@@ -1,4 +1,23 @@
"use strict"; "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) { var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) { 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()); 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 }); Object.defineProperty(exports, "__esModule", { value: true });
const io = __importStar(require("@actions/io")); const io = __importStar(require("@actions/io"));
const exec = __importStar(require("@actions/exec")); const exec = __importStar(require("@actions/exec"));
@@ -28,6 +40,7 @@ class PowerShellToolRunner {
} }
static executePowerShellScriptBlock(scriptBlock, options = {}) { static executePowerShellScriptBlock(scriptBlock, options = {}) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
//Options for error handling
yield exec.exec(`"${PowerShellToolRunner.psPath}" -Command`, [scriptBlock], options); yield exec.exec(`"${PowerShellToolRunner.psPath}" -Command`, [scriptBlock], options);
}); });
} }

View File

@@ -1,9 +1,21 @@
"use strict"; "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) { var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod; if (mod && mod.__esModule) return mod;
var result = {}; var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
result["default"] = mod; __setModuleDefault(result, mod);
return result; return result;
}; };
var __importDefault = (this && this.__importDefault) || function (mod) { var __importDefault = (this && this.__importDefault) || function (mod) {

View File

@@ -1,4 +1,23 @@
"use strict"; "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) { var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) { 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()); 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) { var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod }; return (mod && mod.__esModule) ? mod : { "default": mod };
}; };

View File

@@ -1,4 +1,23 @@
"use strict"; "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) { var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) { 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()); 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 }); Object.defineProperty(exports, "__esModule", { value: true });
const core = __importStar(require("@actions/core")); const core = __importStar(require("@actions/core"));
const exec = __importStar(require("@actions/exec")); const exec = __importStar(require("@actions/exec"));
@@ -27,6 +39,27 @@ var azPSHostEnv = !!process.env.AZUREPS_HOST_ENVIRONMENT ? `${process.env.AZUREP
function main() { function main() {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
try { 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 // Set user agent variable
var isAzCLISuccess = false; var isAzCLISuccess = false;
let usrAgentRepo = `${process.env.GITHUB_REPOSITORY}`; let usrAgentRepo = `${process.env.GITHUB_REPOSITORY}`;
@@ -61,7 +94,6 @@ function main() {
const allowNoSubscriptionsLogin = core.getInput('allow-no-subscriptions').toLowerCase() === "true"; const allowNoSubscriptionsLogin = core.getInput('allow-no-subscriptions').toLowerCase() === "true";
//Check for the credentials in individual parameters in the workflow. //Check for the credentials in individual parameters in the workflow.
var servicePrincipalId = core.getInput('client-id', { required: false }); var servicePrincipalId = core.getInput('client-id', { required: false });
;
var servicePrincipalKey = null; var servicePrincipalKey = null;
var tenantId = core.getInput('tenant-id', { required: false }); var tenantId = core.getInput('tenant-id', { required: false });
var subscriptionId = core.getInput('subscription-id', { required: false }); var subscriptionId = core.getInput('subscription-id', { required: false });
@@ -72,7 +104,7 @@ function main() {
if (servicePrincipalId || tenantId || subscriptionId) { if (servicePrincipalId || tenantId || subscriptionId) {
//If few of the individual credentials (clent_id, tenat_id, subscription_id) are missing in action inputs. //If few of the individual credentials (clent_id, tenat_id, subscription_id) are missing in action inputs.
if (!(servicePrincipalId && tenantId && (subscriptionId || allowNoSubscriptionsLogin))) 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 { else {
if (creds) { if (creds) {
@@ -103,10 +135,13 @@ function main() {
if (enableOIDC) { if (enableOIDC) {
console.log('Using OIDC authentication...'); console.log('Using OIDC authentication...');
//generating ID-token //generating ID-token
federatedToken = yield core.getIDToken('api://AzureADTokenExchange'); let audience = core.getInput('audience', { required: false });
federatedToken = yield core.getIDToken(audience);
if (!!federatedToken) { if (!!federatedToken) {
if (environment != "azurecloud") if (environment != "azurecloud")
throw new Error(`Your current environment - "${environment}" is not supported for OIDC login.`); throw new Error(`Your current environment - "${environment}" is not supported for OIDC login.`);
let [issuer, subjectClaim] = yield jwtParser(federatedToken);
console.log("Federated token details: \n issuer - " + issuer + " \n subject claim - " + subjectClaim);
} }
else { else {
throw new Error("Could not get ID token for authentication."); throw new Error("Could not get ID token for authentication.");
@@ -157,13 +192,13 @@ function main() {
else { else {
commonArgs = commonArgs.concat("-p", servicePrincipalKey); commonArgs = commonArgs.concat("-p", servicePrincipalKey);
} }
yield executeAzCliCommand(`login`, true, {}, commonArgs); yield executeAzCliCommand(`login`, true, loginOptions, commonArgs);
if (!allowNoSubscriptionsLogin) { if (!allowNoSubscriptionsLogin) {
var args = [ var args = [
"--subscription", "--subscription",
subscriptionId subscriptionId
]; ];
yield executeAzCliCommand(`account set`, true, {}, args); yield executeAzCliCommand(`account set`, true, loginOptions, args);
} }
isAzCLISuccess = true; isAzCLISuccess = true;
if (enableAzPSSession) { if (enableAzPSSession) {
@@ -178,12 +213,11 @@ function main() {
} }
catch (error) { catch (error) {
if (!isAzCLISuccess) { 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 and make sure az is istalled on the runner. 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(`Azure PowerShell Login failed. Please check the credentials and make sure az is istalled on the runner. For more information refer https://aka.ms/create-secrets-for-GitHub-workflows"`);
} }
core.setFailed(error);
} }
finally { finally {
// Reset AZURE_HTTP_USER_AGENT // Reset AZURE_HTTP_USER_AGENT
@@ -195,12 +229,15 @@ function main() {
function executeAzCliCommand(command, silent, execOptions = {}, args = []) { function executeAzCliCommand(command, silent, execOptions = {}, args = []) {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
execOptions.silent = !!silent; execOptions.silent = !!silent;
try { yield exec.exec(`"${azPath}" ${command}`, args, execOptions);
yield exec.exec(`"${azPath}" ${command}`, args, execOptions); });
} }
catch (error) { function jwtParser(federatedToken) {
throw new Error(error); return __awaiter(this, void 0, void 0, function* () {
} let tokenPayload = federatedToken.split('.')[1];
let bufferObj = Buffer.from(tokenPayload, "base64");
let decodedPayload = JSON.parse(bufferObj.toString("utf8"));
return [decodedPayload['iss'], decodedPayload['sub']];
}); });
} }
main(); main();

6943
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{ {
"name": "login", "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", "description": "Login Azure wraps the az login, allowing for Azure actions to log into Azure",
"main": "lib/main.js", "main": "lib/main.js",
"scripts": { "scripts": {
@@ -21,6 +21,7 @@
"@actions/core": "1.6.0", "@actions/core": "1.6.0",
"@actions/exec": "^1.0.1", "@actions/exec": "^1.0.1",
"@actions/io": "^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"
} }
} }

View File

@@ -45,10 +45,19 @@ export class ServicePrincipalLogin implements IAzurePowerShellSession {
async login() { async login() {
let output: string = ""; let output: string = "";
let commandStdErr = false;
const options: any = { const options: any = {
listeners: { listeners: {
stdout: (data: Buffer) => { stdout: (data: Buffer) => {
output += data.toString(); output += data.toString();
},
stderr: (data: Buffer) => {
let error = data.toString();
if (error && error.trim().length !== 0)
{
commandStdErr = true;
core.error(error);
}
} }
} }
}; };

View File

@@ -3,7 +3,6 @@ import * as exec from '@actions/exec';
export default class PowerShellToolRunner { export default class PowerShellToolRunner {
static psPath: string; static psPath: string;
static async init() { static async init() {
if(!PowerShellToolRunner.psPath) { if(!PowerShellToolRunner.psPath) {
PowerShellToolRunner.psPath = await io.which("pwsh", true); PowerShellToolRunner.psPath = await io.which("pwsh", true);
@@ -11,6 +10,7 @@ export default class PowerShellToolRunner {
} }
static async executePowerShellScriptBlock(scriptBlock: string, options: any = {}) { static async executePowerShellScriptBlock(scriptBlock: string, options: any = {}) {
//Options for error handling
await exec.exec(`"${PowerShellToolRunner.psPath}" -Command`, [scriptBlock], options) await exec.exec(`"${PowerShellToolRunner.psPath}" -Command`, [scriptBlock], options)
} }
} }

View File

@@ -1,214 +1,238 @@
import * as core from '@actions/core'; import * as core from '@actions/core';
import * as exec from '@actions/exec'; import * as exec from '@actions/exec';
import * as io from '@actions/io'; import { ExecOptions } from '@actions/exec/lib/interfaces';
import { FormatType, SecretParser } from 'actions-secret-parser'; import * as io from '@actions/io';
import { ServicePrincipalLogin } from './PowerShell/ServicePrincipalLogin'; 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 azPath: string;
var azPSHostEnv = !!process.env.AZUREPS_HOST_ENVIRONMENT ? `${process.env.AZUREPS_HOST_ENVIRONMENT}` : ""; 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 { async function main() {
// Set user agent variable try {
var isAzCLISuccess = false; //Options for error handling
let usrAgentRepo = `${process.env.GITHUB_REPOSITORY}`; let commandStdErr = false;
let actionName = 'AzureLogin'; const loginOptions: ExecOptions = {
let userAgentString = (!!prefix ? `${prefix}+` : '') + `GITHUBACTIONS/${actionName}@v1_${usrAgentRepo}`; silent: true,
let azurePSHostEnv = (!!azPSHostEnv ? `${azPSHostEnv}+` : '') + `GITHUBACTIONS/${actionName}@v1_${usrAgentRepo}`; ignoreReturnCode: true,
core.exportVariable('AZURE_HTTP_USER_AGENT', userAgentString); failOnStdErr: true,
core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azurePSHostEnv); listeners: {
stderr: (data: Buffer) => {
azPath = await io.which("az", true); let error = data.toString();
core.debug(`az cli version used: ${azPath}`); //removing the keyword 'ERROR' to avoid duplicates while throwing error
let azureSupportedCloudName = new Set([ if (error.toLowerCase().startsWith('error')) {
"azureusgovernment", error = error.slice(5);
"azurechinacloud", }
"azuregermancloud", // printing error
"azurecloud", if (error && error.trim().length !== 0) {
"azurestack"]); commandStdErr = true;
core.error(error);
let output: string = ""; }
const execOptions: any = { }
listeners: { }
stdout: (data: Buffer) => { }
output += data.toString(); // Set user agent variable
} var isAzCLISuccess = false;
} let usrAgentRepo = `${process.env.GITHUB_REPOSITORY}`;
}; let actionName = 'AzureLogin';
await executeAzCliCommand("--version", true, execOptions); let userAgentString = (!!prefix ? `${prefix}+` : '') + `GITHUBACTIONS/${actionName}@v1_${usrAgentRepo}`;
core.debug(`az cli version used:\n${output}`); let azurePSHostEnv = (!!azPSHostEnv ? `${azPSHostEnv}+` : '') + `GITHUBACTIONS/${actionName}@v1_${usrAgentRepo}`;
core.exportVariable('AZURE_HTTP_USER_AGENT', userAgentString);
let creds = core.getInput('creds', { required: false }); core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azurePSHostEnv);
let secrets = creds ? new SecretParser(creds, FormatType.JSON) : null;
let environment = core.getInput("environment").toLowerCase(); azPath = await io.which("az", true);
const enableAzPSSession = core.getInput('enable-AzPSSession').toLowerCase() === "true"; core.debug(`az cli version used: ${azPath}`);
const allowNoSubscriptionsLogin = core.getInput('allow-no-subscriptions').toLowerCase() === "true"; let azureSupportedCloudName = new Set([
"azureusgovernment",
//Check for the credentials in individual parameters in the workflow. "azurechinacloud",
var servicePrincipalId = core.getInput('client-id', { required: false });; "azuregermancloud",
var servicePrincipalKey = null; "azurecloud",
var tenantId = core.getInput('tenant-id', { required: false }); "azurestack"]);
var subscriptionId = core.getInput('subscription-id', { required: false });
var resourceManagerEndpointUrl = "https://management.azure.com/"; let output: string = "";
var enableOIDC = true; const execOptions: any = {
var federatedToken = null; listeners: {
stdout: (data: Buffer) => {
// If any of the individual credentials (clent_id, tenat_id, subscription_id) is present. output += data.toString();
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))) await executeAzCliCommand("--version", true, execOptions);
throw new Error("Few credentials are missing. ClientId,tenantId are mandatory. SubscriptionId is also mandatory if allow-no-subscriptions is not set."); core.debug(`az cli version used:\n${output}`);
}
else { let creds = core.getInput('creds', { required: false });
if (creds) { let secrets = creds ? new SecretParser(creds, FormatType.JSON) : null;
core.debug('using creds JSON...'); let environment = core.getInput("environment").toLowerCase();
enableOIDC = false; const enableAzPSSession = core.getInput('enable-AzPSSession').toLowerCase() === "true";
servicePrincipalId = secrets.getSecret("$.clientId", true); const allowNoSubscriptionsLogin = core.getInput('allow-no-subscriptions').toLowerCase() === "true";
servicePrincipalKey = secrets.getSecret("$.clientSecret", true);
tenantId = secrets.getSecret("$.tenantId", true); //Check for the credentials in individual parameters in the workflow.
subscriptionId = secrets.getSecret("$.subscriptionId", true); var servicePrincipalId = core.getInput('client-id', { required: false });
resourceManagerEndpointUrl = secrets.getSecret("$.resourceManagerEndpointUrl", false); var servicePrincipalKey = null;
} var tenantId = core.getInput('tenant-id', { required: false });
else { var subscriptionId = core.getInput('subscription-id', { required: false });
throw new Error("Credentials are not passed for Login action."); var resourceManagerEndpointUrl = "https://management.azure.com/";
} var enableOIDC = true;
} var federatedToken = null;
//generic checks
//servicePrincipalKey is only required in non-oidc scenario. // If any of the individual credentials (clent_id, tenat_id, subscription_id) is present.
if (!servicePrincipalId || !tenantId || !(servicePrincipalKey || enableOIDC)) { if (servicePrincipalId || tenantId || subscriptionId) {
throw new Error("Not all values are present in the credentials. Ensure clientId, clientSecret and tenantId are supplied.");
} //If few of the individual credentials (clent_id, tenat_id, subscription_id) are missing in action inputs.
if (!subscriptionId && !allowNoSubscriptionsLogin) { if (!(servicePrincipalId && tenantId && (subscriptionId || allowNoSubscriptionsLogin)))
throw new Error("Not all values are present in the credentials. Ensure subscriptionId is supplied."); throw new Error("Few credentials are missing. ClientId, tenantId are mandatory. SubscriptionId is also mandatory if allow-no-subscriptions is not set.");
} }
if (!azureSupportedCloudName.has(environment)) { else {
throw new Error("Unsupported value for environment is passed.The list of supported values for environment are azureusgovernment', azurechinacloud, azuregermancloud, azurecloud or azurestack"); if (creds) {
} core.debug('using creds JSON...');
enableOIDC = false;
// OIDC specific checks servicePrincipalId = secrets.getSecret("$.clientId", true);
if (enableOIDC) { servicePrincipalKey = secrets.getSecret("$.clientSecret", true);
console.log('Using OIDC authentication...') tenantId = secrets.getSecret("$.tenantId", true);
//generating ID-token subscriptionId = secrets.getSecret("$.subscriptionId", true);
federatedToken = await core.getIDToken('api://AzureADTokenExchange'); resourceManagerEndpointUrl = secrets.getSecret("$.resourceManagerEndpointUrl", false);
if (!!federatedToken) { }
if (environment != "azurecloud") else {
throw new Error(`Your current environment - "${environment}" is not supported for OIDC login.`); throw new Error("Credentials are not passed for Login action.");
} }
else { }
throw new Error("Could not get ID token for authentication."); //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.");
// Attempting Az cli login }
if (environment == "azurestack") { if (!subscriptionId && !allowNoSubscriptionsLogin) {
if (!resourceManagerEndpointUrl) { throw new Error("Not all values are present in the credentials. Ensure subscriptionId is supplied.");
throw new Error("resourceManagerEndpointUrl is a required parameter when environment is defined."); }
} 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");
console.log(`Unregistering cloud: "${environment}" first if it exists`); }
try {
await executeAzCliCommand(`cloud set -n AzureCloud`, true); // OIDC specific checks
await executeAzCliCommand(`cloud unregister -n "${environment}"`, false); if (enableOIDC) {
} console.log('Using OIDC authentication...')
catch (error) { //generating ID-token
console.log(`Ignore cloud not registered error: "${error}"`); let audience = core.getInput('audience', { required: false });
} federatedToken = await core.getIDToken(audience);
if (!!federatedToken) {
console.log(`Registering cloud: "${environment}" with ARM endpoint: "${resourceManagerEndpointUrl}"`); if (environment != "azurecloud")
try { throw new Error(`Your current environment - "${environment}" is not supported for OIDC login.`);
let baseUri = resourceManagerEndpointUrl; let [issuer, subjectClaim] = await jwtParser(federatedToken);
if (baseUri.endsWith('/')) { console.log("Federated token details: \n issuer - " + issuer + " \n subject claim - " + subjectClaim);
baseUri = baseUri.substring(0, baseUri.length - 1); // need to remove trailing / from resourceManagerEndpointUrl to correctly derive suffixes below }
} else {
let suffixKeyvault = ".vault" + baseUri.substring(baseUri.indexOf('.')); // keyvault suffix starts with . throw new Error("Could not get ID token for authentication.");
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);
} // Attempting Az cli login
catch (error) { if (environment == "azurestack") {
core.error(`Error while trying to register cloud "${environment}": "${error}"`); if (!resourceManagerEndpointUrl) {
} throw new Error("resourceManagerEndpointUrl is a required parameter when environment is defined.");
}
console.log(`Done registering cloud: "${environment}"`)
} console.log(`Unregistering cloud: "${environment}" first if it exists`);
try {
await executeAzCliCommand(`cloud set -n "${environment}"`, false); await executeAzCliCommand(`cloud set -n AzureCloud`, true);
console.log(`Done setting cloud: "${environment}"`); await executeAzCliCommand(`cloud unregister -n "${environment}"`, false);
}
// Attempting Az cli login catch (error) {
var commonArgs = ["--service-principal", console.log(`Ignore cloud not registered error: "${error}"`);
"-u", servicePrincipalId, }
"--tenant", tenantId
]; console.log(`Registering cloud: "${environment}" with ARM endpoint: "${resourceManagerEndpointUrl}"`);
if (allowNoSubscriptionsLogin) { try {
commonArgs = commonArgs.concat("--allow-no-subscriptions"); let baseUri = resourceManagerEndpointUrl;
} if (baseUri.endsWith('/')) {
if (enableOIDC) { baseUri = baseUri.substring(0, baseUri.length - 1); // need to remove trailing / from resourceManagerEndpointUrl to correctly derive suffixes below
commonArgs = commonArgs.concat("--federated-token", federatedToken); }
} let suffixKeyvault = ".vault" + baseUri.substring(baseUri.indexOf('.')); // keyvault suffix starts with .
else { let suffixStorage = baseUri.substring(baseUri.indexOf('.') + 1); // storage suffix starts without .
commonArgs = commonArgs.concat("-p", servicePrincipalKey); 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);
await executeAzCliCommand(`login`, true, {}, commonArgs); }
catch (error) {
if (!allowNoSubscriptionsLogin) { core.error(`Error while trying to register cloud "${environment}": "${error}"`);
var args = [ }
"--subscription",
subscriptionId console.log(`Done registering cloud: "${environment}"`)
]; }
await executeAzCliCommand(`account set`, true, {}, args);
} await executeAzCliCommand(`cloud set -n "${environment}"`, false);
isAzCLISuccess = true; console.log(`Done setting cloud: "${environment}"`);
if (enableAzPSSession) {
// Attempting Az PS login // Attempting Az cli login
console.log(`Running Azure PS Login`); var commonArgs = ["--service-principal",
var spnlogin: ServicePrincipalLogin; "-u", servicePrincipalId,
"--tenant", tenantId
spnlogin = new ServicePrincipalLogin( ];
servicePrincipalId, if (allowNoSubscriptionsLogin) {
servicePrincipalKey, commonArgs = commonArgs.concat("--allow-no-subscriptions");
federatedToken, }
tenantId, if (enableOIDC) {
subscriptionId, commonArgs = commonArgs.concat("--federated-token", federatedToken);
allowNoSubscriptionsLogin, }
environment, else {
resourceManagerEndpointUrl); commonArgs = commonArgs.concat("-p", servicePrincipalKey);
await spnlogin.initialize(); }
await spnlogin.login(); await executeAzCliCommand(`login`, true, loginOptions, commonArgs);
}
if (!allowNoSubscriptionsLogin) {
console.log("Login successful."); var args = [
} "--subscription",
catch (error) { subscriptionId
if (!isAzCLISuccess) { ];
core.error("Az CLI Login failed. Please check the credentials. For more information refer https://aka.ms/create-secrets-for-GitHub-workflows"); await executeAzCliCommand(`account set`, true, loginOptions, args);
} }
else { isAzCLISuccess = true;
core.error(`Azure PowerShell Login failed. Please check the credentials. For more information refer https://aka.ms/create-secrets-for-GitHub-workflows"`); if (enableAzPSSession) {
} // Attempting Az PS login
core.setFailed(error); console.log(`Running Azure PS Login`);
} var spnlogin: ServicePrincipalLogin;
finally {
// Reset AZURE_HTTP_USER_AGENT spnlogin = new ServicePrincipalLogin(
core.exportVariable('AZURE_HTTP_USER_AGENT', prefix); servicePrincipalId,
core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azPSHostEnv); servicePrincipalKey,
} federatedToken,
} tenantId,
subscriptionId,
async function executeAzCliCommand( allowNoSubscriptionsLogin,
command: string, environment,
silent?: boolean, resourceManagerEndpointUrl);
execOptions: any = {}, await spnlogin.initialize();
args: any = []) { await spnlogin.login();
execOptions.silent = !!silent; }
try {
await exec.exec(`"${azPath}" ${command}`, args, execOptions); console.log("Login successful.");
} }
catch (error) { catch (error) {
throw new Error(error); if (!isAzCLISuccess) {
} core.setFailed("Az CLI Login failed. Please check the credentials and make sure az is installed on the runner. For more information refer https://aka.ms/create-secrets-for-GitHub-workflows");
} }
else {
main(); core.setFailed(`Azure PowerShell Login failed. Please check the credentials and make sure az is installed on the runner. 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);
}
async function jwtParser(federatedToken: string) {
let tokenPayload = federatedToken.split('.')[1];
let bufferObj = Buffer.from(tokenPayload, "base64");
let decodedPayload = JSON.parse(bufferObj.toString("utf8"));
return [decodedPayload['iss'], decodedPayload['sub']];
}
main();