mirror of
https://github.com/azure/login.git
synced 2026-03-13 18:17:09 -04:00
Compare commits
56 Commits
users/aksm
...
master-cha
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
82829eb8b3 | ||
|
|
f7d7626e95 | ||
|
|
6bc1b5ecb9 | ||
|
|
f8979b3393 | ||
|
|
7f56506e21 | ||
|
|
0cf07a0171 | ||
|
|
c9dca98403 | ||
|
|
177ab1c8df | ||
|
|
5dc2a74a43 | ||
|
|
852ef9dc86 | ||
|
|
92605228cd | ||
|
|
49a928a08c | ||
|
|
b65105a723 | ||
|
|
a0110a77ec | ||
|
|
ed5c47a214 | ||
|
|
0d0ee46f76 | ||
|
|
114a8ef99d | ||
|
|
a78820d812 | ||
|
|
490d296e28 | ||
|
|
1a2f091d94 | ||
|
|
c590679de3 | ||
|
|
b6d623b57e | ||
|
|
bbbe7da52a | ||
|
|
799fd51bc6 | ||
|
|
a9a1dcd2f7 | ||
|
|
e7b36a5753 | ||
|
|
7f6ed87d4a | ||
|
|
c6b99d2720 | ||
|
|
5de298368f | ||
|
|
1ab2192eba | ||
|
|
80970a8c03 | ||
|
|
2e97c69135 | ||
|
|
a614f3cbd0 | ||
|
|
3e306521aa | ||
|
|
56641ce573 | ||
|
|
0d0c4a32af | ||
|
|
14b73ca9b5 | ||
|
|
2e72d699b0 | ||
|
|
ff610a161c | ||
|
|
c72b9ad43b | ||
|
|
9584e50c92 | ||
|
|
d773655321 | ||
|
|
de36370b39 | ||
|
|
bb5ee3d98d | ||
|
|
aa362ff93f | ||
|
|
80b45a252f | ||
|
|
14ff6a1af1 | ||
|
|
4440d80620 | ||
|
|
e7b230d17a | ||
|
|
21f0955fe4 | ||
|
|
45f2ccef11 | ||
|
|
807bb60301 | ||
|
|
8ea3fa2ba0 | ||
|
|
0bf4fdc1f9 | ||
|
|
ee83f1dbb6 | ||
|
|
513cdfa020 |
1
.github/CODEOWNERS
vendored
Normal file
1
.github/CODEOWNERS
vendored
Normal file
@@ -0,0 +1 @@
|
||||
@kaverma @kanika1894 @BALAGA-GAYATRI @pulkitaggarwl
|
||||
10
.github/ISSUE_TEMPLATE/bug-report-feature-request.md
vendored
Normal file
10
.github/ISSUE_TEMPLATE/bug-report-feature-request.md
vendored
Normal file
@@ -0,0 +1,10 @@
|
||||
---
|
||||
name: Bug Report / Feature Request
|
||||
about: Create a report to help us improve
|
||||
title: ''
|
||||
labels: need-to-triage
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
|
||||
21
.github/workflows/auto-triage-issues
vendored
Normal file
21
.github/workflows/auto-triage-issues
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
name: "Auto-Labelling Issues"
|
||||
on:
|
||||
issues:
|
||||
types: [opened, edited]
|
||||
|
||||
jobs:
|
||||
auto_label:
|
||||
runs-on: ubuntu-latest
|
||||
name: Auto-Labelling Issues
|
||||
steps:
|
||||
- name: Label Step
|
||||
uses: larrylawl/Auto-Github-Issue-Labeller@v1.0
|
||||
with:
|
||||
GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}}
|
||||
REPOSITORY: ${{github.repository}}
|
||||
DELTA: "7"
|
||||
CONFIDENCE: "2"
|
||||
FEATURE: "enhancement"
|
||||
BUG: "bug"
|
||||
DOCS: "documentation"
|
||||
|
||||
72
.github/workflows/azure-login-pr-check.yml
vendored
Normal file
72
.github/workflows/azure-login-pr-check.yml
vendored
Normal 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"
|
||||
|
||||
|
||||
36
.github/workflows/defaultLabels.yml
vendored
Normal file
36
.github/workflows/defaultLabels.yml
vendored
Normal file
@@ -0,0 +1,36 @@
|
||||
name: setting-default-labels
|
||||
|
||||
# Controls when the action will run.
|
||||
on:
|
||||
schedule:
|
||||
- cron: "0 0/3 * * *"
|
||||
|
||||
# A workflow run is made up of one or more jobs that can run sequentially or in parallel
|
||||
jobs:
|
||||
build:
|
||||
# The type of runner that the job will run on
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
# Steps represent a sequence of tasks that will be executed as part of the job
|
||||
steps:
|
||||
|
||||
- uses: actions/stale@v3
|
||||
name: Setting issue as idle
|
||||
with:
|
||||
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
stale-issue-message: 'This issue is idle because it has been open for 14 days with no activity.'
|
||||
stale-issue-label: 'idle'
|
||||
days-before-stale: 14
|
||||
days-before-close: -1
|
||||
operations-per-run: 100
|
||||
exempt-issue-labels: 'backlog'
|
||||
|
||||
- uses: actions/stale@v3
|
||||
name: Setting PR as idle
|
||||
with:
|
||||
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
stale-pr-message: 'This PR is idle because it has been open for 14 days with no activity.'
|
||||
stale-pr-label: 'idle'
|
||||
days-before-stale: 14
|
||||
days-before-close: -1
|
||||
operations-per-run: 100
|
||||
171
README.md
171
README.md
@@ -2,7 +2,7 @@
|
||||
|
||||
## 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.
|
||||
|
||||
@@ -12,9 +12,11 @@ Get started today with a [free Azure account](https://azure.com/free/open-source
|
||||
|
||||
# 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.
|
||||
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).
|
||||
|
||||
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.
|
||||
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).
|
||||
|
||||
This repository contains GitHub Action for [Azure Login](https://github.com/Azure/login/blob/master/action.yml).
|
||||
|
||||
@@ -60,7 +62,7 @@ jobs:
|
||||
uses: azure/login@v1
|
||||
with:
|
||||
creds: ${{secrets.AZURE_CREDENTIALS}}
|
||||
enable-AzPSSession: true
|
||||
enable-AzPSSession: true
|
||||
|
||||
- name: Run Az CLI script
|
||||
run: |
|
||||
@@ -74,8 +76,51 @@ jobs:
|
||||
Get-AzVM -ResourceGroupName "ActionsDemo"
|
||||
```
|
||||
|
||||
## Sample to connect to Azure US Government cloud
|
||||
|
||||
```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: 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.
|
||||
|
||||
## Sample Azure Login workflow that to run az cli on Azure Stack Hub
|
||||
|
||||
```yaml
|
||||
|
||||
# File: .github/workflows/workflow.yml
|
||||
|
||||
on: [push]
|
||||
|
||||
name: AzureLoginSample
|
||||
|
||||
jobs:
|
||||
|
||||
build-and-deploy:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: azure/login@v1
|
||||
with:
|
||||
creds: ${{ secrets.AZURE_CREDENTIALS }}
|
||||
environment: 'AzureStack'
|
||||
|
||||
- run: |
|
||||
az webapp list --query "[?state=='Running']"
|
||||
|
||||
```
|
||||
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:
|
||||
|
||||
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.
|
||||
@@ -85,39 +130,48 @@ To function correctly, this service principal must be assigned the [Contributor]
|
||||
The following steps describe how to create the service principal, assign the role, and create a secret in your repository with the resulting credentials.
|
||||
|
||||
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).)
|
||||
|
||||
|
||||
1.1 **(Required ONLY when environment is Azure Stack Hub)** Run the following command to set the SQL Management endpoint to 'not supported'
|
||||
```bash
|
||||
|
||||
az cloud update -n {environmentName} --endpoint-sql-management https://notsupported
|
||||
|
||||
```
|
||||
|
||||
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:
|
||||
|
||||
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}
|
||||
```
|
||||
|
||||
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 you want to use
|
||||
* `{resource-group}` the resource group containing the web app.
|
||||
* `{app-name}` with the name of the web app.
|
||||
For usage with other Azure services (Storage Accounts, Active Directory, etc.)
|
||||
|
||||
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:
|
||||
|
||||
```azurecli
|
||||
```azurecli
|
||||
az ad sp create-for-rbac --name "{sp-name}" --sdk-auth --role contributor \
|
||||
--scopes /subscriptions/{subscription-id}/resourceGroups/{resource-group}
|
||||
```
|
||||
|
||||
For security purposes, however, it's always preferable to grant permissions at the most restrictive scope possible.
|
||||
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": "<GUID>",
|
||||
"clientSecret": "<CLIENT_SECRET_VALUE>",
|
||||
"subscriptionId": "<GUID>",
|
||||
"tenantId": "<GUID>",
|
||||
(...)
|
||||
@@ -126,13 +180,90 @@ The following steps describe how to create the service principal, assign the rol
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
```yaml
|
||||
# File: .github/workflows/workflow.yml
|
||||
|
||||
on: [push]
|
||||
|
||||
name: AzureLoginWithNoSubscriptions
|
||||
|
||||
jobs:
|
||||
|
||||
build-and-deploy:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
|
||||
- uses: azure/login@v1
|
||||
with:
|
||||
creds: ${{ secrets.AZURE_CREDENTIALS }}
|
||||
allow-no-subscriptions: true
|
||||
```
|
||||
## Az logout and security hardening
|
||||
|
||||
This action doesn't implement ```az logout``` by default at the end of execution. However there is no way of tampering the credentials or account information because the github hosted runner is on a VM that will get reimaged for every customer run which gets everything deleted. But if the runner is self-hosted which is not github provided it is recommended to manually logout at the end of the workflow as shown below. More details on security of the runners can be found [here](https://docs.github.com/en/actions/learn-github-actions/security-hardening-for-github-actions#hardening-for-self-hosted-runners).
|
||||
```
|
||||
- name: Azure CLI script
|
||||
uses: azure/CLI@v1
|
||||
with:
|
||||
azcliversion: 2.0.72
|
||||
inlineScript: |
|
||||
az logout
|
||||
az cache purge
|
||||
az account clear
|
||||
```
|
||||
# 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.
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ jest.mock('../../src/PowerShell/Utilities/PowerShellToolRunner');
|
||||
let spnlogin: ServicePrincipalLogin;
|
||||
|
||||
beforeAll(() => {
|
||||
spnlogin = new ServicePrincipalLogin("servicePrincipalID", "servicePrinicipalkey", "tenantId", "subscriptionId", false);
|
||||
spnlogin = new ServicePrincipalLogin("servicePrincipalID", "servicePrinicipalkey", null, "tenantId", "subscriptionId", false, null, null);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
|
||||
17
action.yml
17
action.yml
@@ -4,11 +4,24 @@ description: 'Authenticate to Azure and run your Az CLI or Az
|
||||
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: 'Set this value to true to enable Azure PowerShell Login in addition to Az CLI login'
|
||||
required: false
|
||||
default: false
|
||||
environment:
|
||||
description: 'Name of the environment. Supported values are azurecloud, azurestack, azureusgovernment, azurechinacloud, azuregermancloud. Default being azurecloud'
|
||||
required: false
|
||||
default: azurecloud
|
||||
allow-no-subscriptions:
|
||||
description: 'Set this value to true to enable support for accessing tenants without subscriptions'
|
||||
required: false
|
||||
@@ -18,4 +31,4 @@ branding:
|
||||
color: 'blue'
|
||||
runs:
|
||||
using: 'node12'
|
||||
main: 'lib/main.js'
|
||||
main: 'lib/main.js'
|
||||
@@ -25,11 +25,14 @@ 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) {
|
||||
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;
|
||||
this.resourceManagerEndpointUrl = resourceManagerEndpointUrl;
|
||||
this.allowNoSubscriptionsLogin = allowNoSubscriptionsLogin;
|
||||
}
|
||||
initialize() {
|
||||
@@ -53,10 +56,12 @@ class ServicePrincipalLogin {
|
||||
const args = {
|
||||
servicePrincipalId: this.servicePrincipalId,
|
||||
servicePrincipalKey: this.servicePrincipalKey,
|
||||
federatedToken: this.federatedToken,
|
||||
subscriptionId: this.subscriptionId,
|
||||
environment: ServicePrincipalLogin.environment,
|
||||
environment: this.environment,
|
||||
scopeLevel: ServicePrincipalLogin.scopeLevel,
|
||||
allowNoSubscriptionsLogin: this.allowNoSubscriptionsLogin
|
||||
allowNoSubscriptionsLogin: this.allowNoSubscriptionsLogin,
|
||||
resourceManagerEndpointUrl: this.resourceManagerEndpointUrl
|
||||
};
|
||||
const script = new ScriptBuilder_1.default().getAzPSLoginScript(ServicePrincipalLogin.scheme, this.tenantId, args);
|
||||
yield PowerShellToolRunner_1.default.init();
|
||||
@@ -70,6 +75,5 @@ class ServicePrincipalLogin {
|
||||
}
|
||||
}
|
||||
exports.ServicePrincipalLogin = ServicePrincipalLogin;
|
||||
ServicePrincipalLogin.environment = Constants_1.default.AzureCloud;
|
||||
ServicePrincipalLogin.scopeLevel = Constants_1.default.Subscription;
|
||||
ServicePrincipalLogin.scheme = Constants_1.default.ServicePrincipal;
|
||||
|
||||
@@ -20,9 +20,20 @@ class ScriptBuilder {
|
||||
let command = `Clear-AzContext -Scope Process;
|
||||
Clear-AzContext -Scope CurrentUser -Force -ErrorAction SilentlyContinue;`;
|
||||
if (scheme === Constants_1.default.ServicePrincipal) {
|
||||
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;`;
|
||||
if (args.environment.toLowerCase() == "azurestack") {
|
||||
command += `Add-AzEnvironment -Name ${args.environment} -ARMEndpoint ${args.resourceManagerEndpointUrl} | 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;`;
|
||||
}
|
||||
|
||||
150
lib/main.js
150
lib/main.js
@@ -36,34 +36,141 @@ function main() {
|
||||
core.exportVariable('AZURE_HTTP_USER_AGENT', userAgentString);
|
||||
core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azurePSHostEnv);
|
||||
azPath = yield io.which("az", true);
|
||||
yield executeAzCliCommand("--version");
|
||||
let creds = core.getInput('creds', { required: true });
|
||||
let secrets = new actions_secret_parser_1.SecretParser(creds, actions_secret_parser_1.FormatType.JSON);
|
||||
let servicePrincipalId = secrets.getSecret("$.clientId", false);
|
||||
let servicePrincipalKey = secrets.getSecret("$.clientSecret", true);
|
||||
let tenantId = secrets.getSecret("$.tenantId", false);
|
||||
let subscriptionId = secrets.getSecret("$.subscriptionId", false);
|
||||
core.debug(`az cli version used: ${azPath}`);
|
||||
let azureSupportedCloudName = new Set([
|
||||
"azureusgovernment",
|
||||
"azurechinacloud",
|
||||
"azuregermancloud",
|
||||
"azurecloud",
|
||||
"azurestack"
|
||||
]);
|
||||
let output = "";
|
||||
const execOptions = {
|
||||
listeners: {
|
||||
stdout: (data) => {
|
||||
output += data.toString();
|
||||
}
|
||||
}
|
||||
};
|
||||
yield executeAzCliCommand("--version", true, execOptions);
|
||||
core.debug(`az cli version used:\n${output}`);
|
||||
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.");
|
||||
}
|
||||
if (!subscriptionId && !allowNoSubscriptionsLogin) {
|
||||
throw new Error("Not all values are present in the creds object. Ensure subscriptionId is supplied.");
|
||||
}
|
||||
// Attempting Az cli login
|
||||
if (allowNoSubscriptionsLogin) {
|
||||
yield executeAzCliCommand(`login --allow-no-subscriptions --service-principal -u "${servicePrincipalId}" -p "${servicePrincipalKey}" --tenant "${tenantId}"`, 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 {
|
||||
yield executeAzCliCommand(`login --service-principal -u "${servicePrincipalId}" -p "${servicePrincipalKey}" --tenant "${tenantId}"`, true);
|
||||
yield executeAzCliCommand(`account set --subscription "${subscriptionId}"`, true);
|
||||
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 = 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) {
|
||||
throw new Error("resourceManagerEndpointUrl is a required parameter when environment is defined.");
|
||||
}
|
||||
console.log(`Unregistering cloud: "${environment}" first if it exists`);
|
||||
try {
|
||||
yield executeAzCliCommand(`cloud set -n AzureCloud`, true);
|
||||
yield executeAzCliCommand(`cloud unregister -n "${environment}"`, false);
|
||||
}
|
||||
catch (error) {
|
||||
console.log(`Ignore cloud not registered error: "${error}"`);
|
||||
}
|
||||
console.log(`Registering cloud: "${environment}" with ARM endpoint: "${resourceManagerEndpointUrl}"`);
|
||||
try {
|
||||
let baseUri = resourceManagerEndpointUrl;
|
||||
if (baseUri.endsWith('/')) {
|
||||
baseUri = baseUri.substring(0, baseUri.length - 1); // need to remove trailing / from resourceManagerEndpointUrl to correctly derive suffixes below
|
||||
}
|
||||
let suffixKeyvault = ".vault" + baseUri.substring(baseUri.indexOf('.')); // keyvault suffix starts with .
|
||||
let suffixStorage = baseUri.substring(baseUri.indexOf('.') + 1); // storage suffix starts without .
|
||||
let profileVersion = "2019-03-01-hybrid";
|
||||
yield executeAzCliCommand(`cloud register -n "${environment}" --endpoint-resource-manager "${resourceManagerEndpointUrl}" --suffix-keyvault-dns "${suffixKeyvault}" --suffix-storage-endpoint "${suffixStorage}" --profile "${profileVersion}"`, false);
|
||||
}
|
||||
catch (error) {
|
||||
core.error(`Error while trying to register cloud "${environment}": "${error}"`);
|
||||
}
|
||||
console.log(`Done registering cloud: "${environment}"`);
|
||||
}
|
||||
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) {
|
||||
commonArgs = commonArgs.concat("--allow-no-subscriptions");
|
||||
}
|
||||
if (enableOIDC) {
|
||||
commonArgs = commonArgs.concat("--federated-token", federatedToken);
|
||||
}
|
||||
else {
|
||||
commonArgs = commonArgs.concat("-p", servicePrincipalKey);
|
||||
}
|
||||
yield executeAzCliCommand(`login`, true, {}, commonArgs);
|
||||
if (!allowNoSubscriptionsLogin) {
|
||||
var args = [
|
||||
"--subscription",
|
||||
subscriptionId
|
||||
];
|
||||
yield executeAzCliCommand(`account set`, true, {}, args);
|
||||
}
|
||||
isAzCLISuccess = true;
|
||||
if (enableAzPSSession) {
|
||||
// Attempting Az PS login
|
||||
console.log(`Running Azure PS Login`);
|
||||
const spnlogin = new ServicePrincipalLogin_1.ServicePrincipalLogin(servicePrincipalId, servicePrincipalKey, tenantId, subscriptionId, allowNoSubscriptionsLogin);
|
||||
var spnlogin;
|
||||
spnlogin = new ServicePrincipalLogin_1.ServicePrincipalLogin(servicePrincipalId, servicePrincipalKey, federatedToken, tenantId, subscriptionId, allowNoSubscriptionsLogin, environment, resourceManagerEndpointUrl);
|
||||
yield spnlogin.initialize();
|
||||
yield spnlogin.login();
|
||||
}
|
||||
@@ -85,10 +192,11 @@ function main() {
|
||||
}
|
||||
});
|
||||
}
|
||||
function executeAzCliCommand(command, silent) {
|
||||
function executeAzCliCommand(command, silent, execOptions = {}, args = []) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
execOptions.silent = !!silent;
|
||||
try {
|
||||
yield exec.exec(`"${azPath}" ${command}`, [], { silent: !!silent });
|
||||
yield exec.exec(`"${azPath}" ${command}`, args, execOptions);
|
||||
}
|
||||
catch (error) {
|
||||
throw new Error(error);
|
||||
|
||||
6210
package-lock.json
generated
6210
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -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"
|
||||
|
||||
@@ -6,24 +6,33 @@ import ScriptBuilder from './Utilities/ScriptBuilder';
|
||||
import Constants from './Constants';
|
||||
|
||||
export class ServicePrincipalLogin implements IAzurePowerShellSession {
|
||||
static readonly environment: string = Constants.AzureCloud;
|
||||
static readonly scopeLevel: string = Constants.Subscription;
|
||||
static readonly scheme: string = Constants.ServicePrincipal;
|
||||
environment: string;
|
||||
servicePrincipalId: string;
|
||||
servicePrincipalKey: string;
|
||||
tenantId: string;
|
||||
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) {
|
||||
allowNoSubscriptionsLogin: boolean,
|
||||
environment: string,
|
||||
resourceManagerEndpointUrl: string) {
|
||||
|
||||
this.servicePrincipalId = servicePrincipalId;
|
||||
this.servicePrincipalKey = servicePrincipalKey;
|
||||
this.federatedToken = federatedToken;
|
||||
this.tenantId = tenantId;
|
||||
this.subscriptionId = subscriptionId;
|
||||
this.environment = environment;
|
||||
this.resourceManagerEndpointUrl = resourceManagerEndpointUrl;
|
||||
this.allowNoSubscriptionsLogin = allowNoSubscriptionsLogin;
|
||||
}
|
||||
|
||||
@@ -46,10 +55,12 @@ export class ServicePrincipalLogin implements IAzurePowerShellSession {
|
||||
const args: any = {
|
||||
servicePrincipalId: this.servicePrincipalId,
|
||||
servicePrincipalKey: this.servicePrincipalKey,
|
||||
federatedToken: this.federatedToken,
|
||||
subscriptionId: this.subscriptionId,
|
||||
environment: ServicePrincipalLogin.environment,
|
||||
environment: this.environment,
|
||||
scopeLevel: ServicePrincipalLogin.scopeLevel,
|
||||
allowNoSubscriptionsLogin: this.allowNoSubscriptionsLogin
|
||||
allowNoSubscriptionsLogin: this.allowNoSubscriptionsLogin,
|
||||
resourceManagerEndpointUrl: this.resourceManagerEndpointUrl
|
||||
}
|
||||
const script: string = new ScriptBuilder().getAzPSLoginScript(ServicePrincipalLogin.scheme, this.tenantId, args);
|
||||
await PowerShellToolRunner.init();
|
||||
|
||||
@@ -8,14 +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) {
|
||||
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;`;
|
||||
|
||||
if (args.environment.toLowerCase() == "azurestack") {
|
||||
command += `Add-AzEnvironment -Name ${args.environment} -ARMEndpoint ${args.resourceManagerEndpointUrl} | 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"
|
||||
@@ -27,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;
|
||||
}
|
||||
@@ -48,4 +63,5 @@ export default class ScriptBuilder {
|
||||
core.debug(`GetLatestModuleScript: ${this.script}`);
|
||||
return this.script;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
180
src/main.ts
180
src/main.ts
@@ -1,7 +1,6 @@
|
||||
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';
|
||||
|
||||
@@ -21,62 +20,195 @@ async function main() {
|
||||
core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azurePSHostEnv);
|
||||
|
||||
azPath = await io.which("az", true);
|
||||
await executeAzCliCommand("--version");
|
||||
core.debug(`az cli version used: ${azPath}`);
|
||||
let azureSupportedCloudName = new Set([
|
||||
"azureusgovernment",
|
||||
"azurechinacloud",
|
||||
"azuregermancloud",
|
||||
"azurecloud",
|
||||
"azurestack"]);
|
||||
|
||||
let creds = core.getInput('creds', { required: true });
|
||||
let secrets = new SecretParser(creds, FormatType.JSON);
|
||||
let servicePrincipalId = secrets.getSecret("$.clientId", false);
|
||||
let servicePrincipalKey = secrets.getSecret("$.clientSecret", true);
|
||||
let tenantId = secrets.getSecret("$.tenantId", false);
|
||||
let subscriptionId = secrets.getSecret("$.subscriptionId", false);
|
||||
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";
|
||||
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.");
|
||||
}
|
||||
}
|
||||
|
||||
// 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) {
|
||||
await executeAzCliCommand(`login --allow-no-subscriptions --service-principal -u "${servicePrincipalId}" -p "${servicePrincipalKey}" --tenant "${tenantId}"`, true);
|
||||
commonArgs = commonArgs.concat("--allow-no-subscriptions");
|
||||
}
|
||||
if (enableOIDC) {
|
||||
commonArgs = commonArgs.concat("--federated-token", federatedToken);
|
||||
}
|
||||
else {
|
||||
await executeAzCliCommand(`login --service-principal -u "${servicePrincipalId}" -p "${servicePrincipalKey}" --tenant "${tenantId}"`, true);
|
||||
await executeAzCliCommand(`account set --subscription "${subscriptionId}"`, true);
|
||||
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, allowNoSubscriptionsLogin);
|
||||
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) {
|
||||
|
||||
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 {
|
||||
}
|
||||
else {
|
||||
core.error(`Azure PowerShell Login failed. Please check the credentials. For more information refer https://aka.ms/create-secrets-for-GitHub-workflows"`);
|
||||
}
|
||||
core.setFailed(error);
|
||||
} finally {
|
||||
}
|
||||
finally {
|
||||
// Reset AZURE_HTTP_USER_AGENT
|
||||
core.exportVariable('AZURE_HTTP_USER_AGENT', prefix);
|
||||
core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azPSHostEnv);
|
||||
}
|
||||
}
|
||||
|
||||
async function executeAzCliCommand(command: string, silent?: boolean) {
|
||||
async function executeAzCliCommand(
|
||||
command: string,
|
||||
silent?: boolean,
|
||||
execOptions: any = {},
|
||||
args: any = []) {
|
||||
execOptions.silent = !!silent;
|
||||
try {
|
||||
await exec.exec(`"${azPath}" ${command}`, [], {silent: !!silent});
|
||||
await exec.exec(`"${azPath}" ${command}`, args, execOptions);
|
||||
}
|
||||
catch(error) {
|
||||
catch (error) {
|
||||
throw new Error(error);
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
main();
|
||||
Reference in New Issue
Block a user