mirror of
https://github.com/azure/login.git
synced 2026-03-13 18:17:09 -04:00
Compare commits
2 Commits
readme-cha
...
users/aksm
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
91bb68642a | ||
|
|
1e2534e0f4 |
1
.github/CODEOWNERS
vendored
1
.github/CODEOWNERS
vendored
@@ -1 +0,0 @@
|
||||
@kaverma @kanika1894 @BALAGA-GAYATRI @pulkitaggarwl
|
||||
@@ -1,10 +0,0 @@
|
||||
---
|
||||
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
21
.github/workflows/auto-triage-issues
vendored
@@ -1,21 +0,0 @@
|
||||
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
72
.github/workflows/azure-login-pr-check.yml
vendored
@@ -1,72 +0,0 @@
|
||||
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
36
.github/workflows/defaultLabels.yml
vendored
@@ -1,36 +0,0 @@
|
||||
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
|
||||
299
README.md
299
README.md
@@ -2,36 +2,25 @@
|
||||
|
||||
## 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
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
- 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 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.
|
||||
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.
|
||||
|
||||
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
|
||||
|
||||
```yaml
|
||||
|
||||
# File: .github/workflows/workflow.yml
|
||||
|
||||
on: [push]
|
||||
@@ -43,268 +32,108 @@ jobs:
|
||||
build-and-deploy:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
|
||||
|
||||
- uses: azure/login@v1
|
||||
with:
|
||||
creds: ${{ secrets.AZURE_CREDENTIALS }}
|
||||
|
||||
|
||||
- run: |
|
||||
az webapp list --query "[?state=='Running']"
|
||||
|
||||
```
|
||||
|
||||
## Sample workflow that uses Azure login action to run Azure PowerShell
|
||||
|
||||
```yaml
|
||||
|
||||
# File: .github/workflows/workflow.yml
|
||||
|
||||
on: [push]
|
||||
|
||||
name: AzurePowerShellLoginSample
|
||||
name: AzurePowerShellSample
|
||||
|
||||
jobs:
|
||||
|
||||
build:
|
||||
build-and-deploy:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
|
||||
|
||||
- name: Login via Az module
|
||||
uses: azure/login@v1
|
||||
with:
|
||||
creds: ${{secrets.AZURE_CREDENTIALS}}
|
||||
enable-AzPSSession: true
|
||||
|
||||
- run: |
|
||||
Get-AzVM -ResourceGroupName "ResourceGroup11"
|
||||
|
||||
```
|
||||
## Sample workflow that uses Azure login action using OIDC to run az cli (Linux)
|
||||
|
||||
```yaml
|
||||
# File: .github/workflows/OIDC_workflow.yml
|
||||
- name: Run Az CLI script
|
||||
run: |
|
||||
az webapp list --query "[?state=='Running']"
|
||||
|
||||
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.4.1
|
||||
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.4.1
|
||||
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
|
||||
|
||||
```yaml
|
||||
- name: Login to Azure US Gov Cloud with CLI
|
||||
uses: azure/login@v1
|
||||
- name: Run Azure PowerShell script
|
||||
uses: azure/powershell@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
|
||||
azPSVersion: '3.1.0'
|
||||
inlineScript: |
|
||||
Get-AzVM -ResourceGroupName "ActionsDemo"
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
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).)
|
||||
|
||||
### Configure a service principal with a secret:
|
||||
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 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.
|
||||
```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.
|
||||
|
||||
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
|
||||
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`).
|
||||
|
||||
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
|
||||
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.
|
||||
|
||||
# The command should output a JSON object similar to this:
|
||||
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:
|
||||
|
||||
{
|
||||
"clientId": "<GUID>",
|
||||
"clientSecret": "<GUID>",
|
||||
"subscriptionId": "<GUID>",
|
||||
"tenantId": "<GUID>",
|
||||
(...)
|
||||
}
|
||||
|
||||
```
|
||||
* 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)
|
||||
```azurecli
|
||||
az ad sp create-for-rbac --name "{sp-name}" --sdk-auth --role contributor \
|
||||
--scopes /subscriptions/{subscription-id}/resourceGroups/{resource-group}
|
||||
```
|
||||
|
||||
### Configure a service principal with a Federated Credential to use OIDC based authentication:
|
||||
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):
|
||||
|
||||
You can add federated credentials in the Azure portal or with the Microsoft Graph REST API.
|
||||
```json
|
||||
{
|
||||
"clientId": "<GUID>",
|
||||
"clientSecret": "<GUID>",
|
||||
"subscriptionId": "<GUID>",
|
||||
"tenantId": "<GUID>",
|
||||
(...)
|
||||
}
|
||||
```
|
||||
|
||||
#### Azure portal
|
||||
1. Go to **Certificates and secrets**. In the **Federated credentials** tab, select **Add credential**.
|
||||
1. The **Add a credential** blade opens.
|
||||
1. In the **Federated credential scenario** box select **GitHub actions deploying Azure resources**.
|
||||
1. Specify the **Organization** and **Repository** for your GitHub Actions workflow which needs to access the Azure resources scoped by this App (Service Principal)
|
||||
1. 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).
|
||||
1. Add a **Name** for the federated credential.
|
||||
1. Click **Add** to configure the federated credential.
|
||||
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.
|
||||
|
||||
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).
|
||||
5. Paste the entire JSON object produced by the `az ad sp create-for-rbac` command as the secret value and save the secret.
|
||||
|
||||
#### 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
|
||||
|
||||
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
|
||||
# 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
|
||||
```
|
||||
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.
|
||||
|
||||
# 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.
|
||||
|
||||
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
|
||||
contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.
|
||||
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.
|
||||
|
||||
@@ -5,7 +5,7 @@ jest.mock('../../src/PowerShell/Utilities/PowerShellToolRunner');
|
||||
let spnlogin: ServicePrincipalLogin;
|
||||
|
||||
beforeAll(() => {
|
||||
spnlogin = new ServicePrincipalLogin("servicePrincipalID", "servicePrinicipalkey", null, "tenantId", "subscriptionId", false, null, null);
|
||||
spnlogin = new ServicePrincipalLogin("servicePrincipalID", "servicePrinicipalkey", "tenantId", "subscriptionId", false);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
|
||||
21
action.yml
21
action.yml
@@ -4,35 +4,18 @@ 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: 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
|
||||
required: true
|
||||
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
|
||||
default: false
|
||||
audience:
|
||||
description: 'Provide audience field for access-token. Default value is api://AzureADTokenExchange'
|
||||
required: false
|
||||
default: 'api://AzureADTokenExchange'
|
||||
branding:
|
||||
icon: 'login.svg'
|
||||
color: 'blue'
|
||||
runs:
|
||||
using: 'node12'
|
||||
main: 'lib/main.js'
|
||||
main: 'lib/main.js'
|
||||
|
||||
@@ -1,23 +1,4 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
@@ -27,25 +8,28 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
|
||||
result["default"] = mod;
|
||||
return result;
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ServicePrincipalLogin = void 0;
|
||||
const core = __importStar(require("@actions/core"));
|
||||
const Utils_1 = __importDefault(require("./Utilities/Utils"));
|
||||
const PowerShellToolRunner_1 = __importDefault(require("./Utilities/PowerShellToolRunner"));
|
||||
const ScriptBuilder_1 = __importDefault(require("./Utilities/ScriptBuilder"));
|
||||
const Constants_1 = __importDefault(require("./Constants"));
|
||||
class ServicePrincipalLogin {
|
||||
constructor(servicePrincipalId, servicePrincipalKey, federatedToken, tenantId, subscriptionId, allowNoSubscriptionsLogin, environment, resourceManagerEndpointUrl) {
|
||||
constructor(servicePrincipalId, servicePrincipalKey, tenantId, subscriptionId, allowNoSubscriptionsLogin) {
|
||||
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() {
|
||||
@@ -59,30 +43,20 @@ class ServicePrincipalLogin {
|
||||
login() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
let output = "";
|
||||
let commandStdErr = false;
|
||||
const options = {
|
||||
listeners: {
|
||||
stdout: (data) => {
|
||||
output += data.toString();
|
||||
},
|
||||
stderr: (data) => {
|
||||
let error = data.toString();
|
||||
if (error && error.trim().length !== 0) {
|
||||
commandStdErr = true;
|
||||
core.error(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
const args = {
|
||||
servicePrincipalId: this.servicePrincipalId,
|
||||
servicePrincipalKey: this.servicePrincipalKey,
|
||||
federatedToken: this.federatedToken,
|
||||
subscriptionId: this.subscriptionId,
|
||||
environment: this.environment,
|
||||
environment: ServicePrincipalLogin.environment,
|
||||
scopeLevel: ServicePrincipalLogin.scopeLevel,
|
||||
allowNoSubscriptionsLogin: this.allowNoSubscriptionsLogin,
|
||||
resourceManagerEndpointUrl: this.resourceManagerEndpointUrl
|
||||
allowNoSubscriptionsLogin: this.allowNoSubscriptionsLogin
|
||||
};
|
||||
const script = new ScriptBuilder_1.default().getAzPSLoginScript(ServicePrincipalLogin.scheme, this.tenantId, args);
|
||||
yield PowerShellToolRunner_1.default.init();
|
||||
@@ -96,5 +70,6 @@ class ServicePrincipalLogin {
|
||||
}
|
||||
}
|
||||
exports.ServicePrincipalLogin = ServicePrincipalLogin;
|
||||
ServicePrincipalLogin.environment = Constants_1.default.AzureCloud;
|
||||
ServicePrincipalLogin.scopeLevel = Constants_1.default.Subscription;
|
||||
ServicePrincipalLogin.scheme = Constants_1.default.ServicePrincipal;
|
||||
|
||||
@@ -1,23 +1,4 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
@@ -27,6 +8,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
|
||||
result["default"] = mod;
|
||||
return result;
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const io = __importStar(require("@actions/io"));
|
||||
const exec = __importStar(require("@actions/exec"));
|
||||
@@ -40,7 +28,6 @@ class PowerShellToolRunner {
|
||||
}
|
||||
static executePowerShellScriptBlock(scriptBlock, options = {}) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
//Options for error handling
|
||||
yield exec.exec(`"${PowerShellToolRunner.psPath}" -Command`, [scriptBlock], options);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,21 +1,9 @@
|
||||
"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);
|
||||
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) {
|
||||
@@ -32,20 +20,9 @@ class ScriptBuilder {
|
||||
let command = `Clear-AzContext -Scope Process;
|
||||
Clear-AzContext -Scope CurrentUser -Force -ErrorAction SilentlyContinue;`;
|
||||
if (scheme === Constants_1.default.ServicePrincipal) {
|
||||
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
|
||||
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.scopeLevel === Constants_1.default.Subscription && !args.allowNoSubscriptionsLogin) {
|
||||
command += `Set-AzContext -SubscriptionId '${args.subscriptionId}' -TenantId '${tenantId}' | out-null;`;
|
||||
}
|
||||
|
||||
@@ -1,23 +1,4 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
@@ -27,6 +8,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
|
||||
result["default"] = mod;
|
||||
return result;
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
|
||||
194
lib/main.js
194
lib/main.js
@@ -1,23 +1,4 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function (o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
Object.defineProperty(o, k2, { enumerable: true, get: function () { return m[k]; } });
|
||||
}) : (function (o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function (o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function (o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
@@ -27,6 +8,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
|
||||
result["default"] = mod;
|
||||
return result;
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const core = __importStar(require("@actions/core"));
|
||||
const exec = __importStar(require("@actions/exec"));
|
||||
@@ -39,27 +27,6 @@ var azPSHostEnv = !!process.env.AZUREPS_HOST_ENVIRONMENT ? `${process.env.AZUREP
|
||||
function main() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
try {
|
||||
//Options for error handling
|
||||
let commandStdErr = false;
|
||||
const loginOptions = {
|
||||
silent: true,
|
||||
ignoreReturnCode: true,
|
||||
failOnStdErr: true,
|
||||
listeners: {
|
||||
stderr: (data) => {
|
||||
let error = data.toString();
|
||||
//removing the keyword 'ERROR' to avoid duplicates while throwing error
|
||||
if (error.toLowerCase().startsWith('error')) {
|
||||
error = error.slice(5);
|
||||
}
|
||||
// printing error
|
||||
if (error && error.trim().length !== 0) {
|
||||
commandStdErr = true;
|
||||
core.error(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
// Set user agent variable
|
||||
var isAzCLISuccess = false;
|
||||
let usrAgentRepo = `${process.env.GITHUB_REPOSITORY}`;
|
||||
@@ -69,141 +36,45 @@ function main() {
|
||||
core.exportVariable('AZURE_HTTP_USER_AGENT', userAgentString);
|
||||
core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azurePSHostEnv);
|
||||
azPath = yield io.which("az", true);
|
||||
core.debug(`az cli version used: ${azPath}`);
|
||||
let azureSupportedCloudName = new Set([
|
||||
"azureusgovernment",
|
||||
"azurechinacloud",
|
||||
"azuregermancloud",
|
||||
"azurecloud",
|
||||
"azurestack"
|
||||
]);
|
||||
let output = "";
|
||||
const execOptions = {
|
||||
const options = {
|
||||
listeners: {
|
||||
stdout: (data) => {
|
||||
output += data.toString();
|
||||
}
|
||||
}
|
||||
};
|
||||
yield executeAzCliCommand("--version", true, execOptions);
|
||||
yield executeAzCliCommand("--version", true, options);
|
||||
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();
|
||||
|
||||
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);
|
||||
const enableAzPSSession = core.getInput('enable-AzPSSession').toLowerCase() === "true";
|
||||
const allowNoSubscriptionsLogin = core.getInput('allow-no-subscriptions').toLowerCase() === "true";
|
||||
//Check for the credentials in individual parameters in the workflow.
|
||||
var servicePrincipalId = core.getInput('client-id', { required: false });
|
||||
var servicePrincipalKey = null;
|
||||
var tenantId = core.getInput('tenant-id', { required: false });
|
||||
var subscriptionId = core.getInput('subscription-id', { required: false });
|
||||
var resourceManagerEndpointUrl = "https://management.azure.com/";
|
||||
var enableOIDC = true;
|
||||
var federatedToken = null;
|
||||
// If any of the individual credentials (clent_id, tenat_id, subscription_id) is present.
|
||||
if (servicePrincipalId || tenantId || subscriptionId) {
|
||||
//If few of the individual credentials (clent_id, tenat_id, subscription_id) are missing in action inputs.
|
||||
if (!(servicePrincipalId && tenantId && (subscriptionId || allowNoSubscriptionsLogin)))
|
||||
throw new Error("Few credentials are missing. ClientId, tenantId are mandatory. SubscriptionId is also mandatory if allow-no-subscriptions is not set.");
|
||||
}
|
||||
else {
|
||||
if (creds) {
|
||||
core.debug('using creds JSON...');
|
||||
enableOIDC = false;
|
||||
servicePrincipalId = secrets.getSecret("$.clientId", true);
|
||||
servicePrincipalKey = secrets.getSecret("$.clientSecret", true);
|
||||
tenantId = secrets.getSecret("$.tenantId", true);
|
||||
subscriptionId = secrets.getSecret("$.subscriptionId", true);
|
||||
resourceManagerEndpointUrl = secrets.getSecret("$.resourceManagerEndpointUrl", false);
|
||||
}
|
||||
else {
|
||||
throw new Error("Credentials are not passed for Login action.");
|
||||
}
|
||||
}
|
||||
//generic checks
|
||||
//servicePrincipalKey is only required in non-oidc scenario.
|
||||
if (!servicePrincipalId || !tenantId || !(servicePrincipalKey || enableOIDC)) {
|
||||
throw new Error("Not all values are present in the credentials. Ensure clientId, clientSecret and tenantId are supplied.");
|
||||
|
||||
if (!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 credentials. Ensure subscriptionId is supplied.");
|
||||
}
|
||||
if (!azureSupportedCloudName.has(environment)) {
|
||||
throw new Error("Unsupported value for environment is passed.The list of supported values for environment are ‘azureusgovernment', ‘azurechinacloud’, ‘azuregermancloud’, ‘azurecloud’ or ’azurestack’");
|
||||
}
|
||||
// OIDC specific checks
|
||||
if (enableOIDC) {
|
||||
console.log('Using OIDC authentication...');
|
||||
//generating ID-token
|
||||
let audience = core.getInput('audience', { required: false });
|
||||
federatedToken = yield core.getIDToken(audience);
|
||||
if (!!federatedToken) {
|
||||
if (environment != "azurecloud")
|
||||
throw new Error(`Your current environment - "${environment}" is not supported for OIDC login.`);
|
||||
}
|
||||
else {
|
||||
throw new Error("Could not get ID token for authentication.");
|
||||
}
|
||||
throw new Error("Not all values are present in the creds object. Ensure subscriptionId is supplied.");
|
||||
}
|
||||
// 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);
|
||||
yield executeAzCliCommand(`login --allow-no-subscriptions --service-principal -u "${servicePrincipalId}" -p "${servicePrincipalKey}" --tenant "${tenantId}"`, true);
|
||||
}
|
||||
else {
|
||||
commonArgs = commonArgs.concat("-p", servicePrincipalKey);
|
||||
}
|
||||
yield executeAzCliCommand(`login`, true, loginOptions, commonArgs);
|
||||
if (!allowNoSubscriptionsLogin) {
|
||||
var args = [
|
||||
"--subscription",
|
||||
subscriptionId
|
||||
];
|
||||
yield executeAzCliCommand(`account set`, true, loginOptions, args);
|
||||
yield executeAzCliCommand(`login --service-principal -u "${servicePrincipalId}" -p "${servicePrincipalKey}" --tenant "${tenantId}"`, true);
|
||||
yield executeAzCliCommand(`account set --subscription "${subscriptionId}"`, true);
|
||||
}
|
||||
isAzCLISuccess = true;
|
||||
if (enableAzPSSession) {
|
||||
// Attempting Az PS login
|
||||
console.log(`Running Azure PS Login`);
|
||||
var spnlogin;
|
||||
spnlogin = new ServicePrincipalLogin_1.ServicePrincipalLogin(servicePrincipalId, servicePrincipalKey, federatedToken, tenantId, subscriptionId, allowNoSubscriptionsLogin, environment, resourceManagerEndpointUrl);
|
||||
const spnlogin = new ServicePrincipalLogin_1.ServicePrincipalLogin(servicePrincipalId, servicePrincipalKey, tenantId, subscriptionId, allowNoSubscriptionsLogin);
|
||||
yield spnlogin.initialize();
|
||||
yield spnlogin.login();
|
||||
}
|
||||
@@ -211,11 +82,12 @@ function main() {
|
||||
}
|
||||
catch (error) {
|
||||
if (!isAzCLISuccess) {
|
||||
core.setFailed("Az CLI Login failed. Please check the credentials. For more information refer https://aka.ms/create-secrets-for-GitHub-workflows");
|
||||
core.error("Az CLI Login failed. Please check the credentials. For more information refer https://aka.ms/create-secrets-for-GitHub-workflows");
|
||||
}
|
||||
else {
|
||||
core.setFailed(`Azure PowerShell Login failed. Please check the credentials. For more information refer https://aka.ms/create-secrets-for-GitHub-workflows"`);
|
||||
core.error(`Azure PowerShell Login failed. Please check the credentials. For more information refer https://aka.ms/create-secrets-for-GitHub-workflows"`);
|
||||
}
|
||||
core.setFailed(error);
|
||||
}
|
||||
finally {
|
||||
// Reset AZURE_HTTP_USER_AGENT
|
||||
@@ -224,10 +96,16 @@ function main() {
|
||||
}
|
||||
});
|
||||
}
|
||||
function executeAzCliCommand(command, silent, execOptions = {}, args = []) {
|
||||
|
||||
function executeAzCliCommand(command, silent, options = {}) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
execOptions.silent = !!silent;
|
||||
yield exec.exec(`"${azPath}" ${command}`, args, execOptions);
|
||||
options.silent = !!silent;
|
||||
try {
|
||||
yield exec.exec(`"${azPath}" ${command}`, [], options);
|
||||
}
|
||||
catch (error) {
|
||||
throw new Error(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
main();
|
||||
|
||||
9633
package-lock.json
generated
9633
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "login",
|
||||
"version": "1.0.0",
|
||||
"version": "1.1.0",
|
||||
"description": "Login Azure wraps the az login, allowing for Azure actions to log into Azure",
|
||||
"main": "lib/main.js",
|
||||
"scripts": {
|
||||
@@ -18,10 +18,9 @@
|
||||
"typescript": "^3.6.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"@actions/core": "1.6.0",
|
||||
"@actions/core": "^1.2.6",
|
||||
"@actions/exec": "^1.0.1",
|
||||
"@actions/io": "^1.0.1",
|
||||
"actions-secret-parser": "^1.0.2",
|
||||
"package-lock": "^1.0.3"
|
||||
"actions-secret-parser": "^1.0.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,33 +6,24 @@ 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,
|
||||
federatedToken: string,
|
||||
tenantId: string,
|
||||
constructor(servicePrincipalId: string,
|
||||
servicePrincipalKey: string,
|
||||
tenantId: string,
|
||||
subscriptionId: string,
|
||||
allowNoSubscriptionsLogin: boolean,
|
||||
environment: string,
|
||||
resourceManagerEndpointUrl: string) {
|
||||
|
||||
allowNoSubscriptionsLogin: boolean) {
|
||||
this.servicePrincipalId = servicePrincipalId;
|
||||
this.servicePrincipalKey = servicePrincipalKey;
|
||||
this.federatedToken = federatedToken;
|
||||
this.tenantId = tenantId;
|
||||
this.subscriptionId = subscriptionId;
|
||||
this.environment = environment;
|
||||
this.resourceManagerEndpointUrl = resourceManagerEndpointUrl;
|
||||
this.allowNoSubscriptionsLogin = allowNoSubscriptionsLogin;
|
||||
}
|
||||
|
||||
@@ -45,31 +36,20 @@ export class ServicePrincipalLogin implements IAzurePowerShellSession {
|
||||
|
||||
async login() {
|
||||
let output: string = "";
|
||||
let commandStdErr = false;
|
||||
const options: any = {
|
||||
listeners: {
|
||||
stdout: (data: Buffer) => {
|
||||
output += data.toString();
|
||||
},
|
||||
stderr: (data: Buffer) => {
|
||||
let error = data.toString();
|
||||
if (error && error.trim().length !== 0)
|
||||
{
|
||||
commandStdErr = true;
|
||||
core.error(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
const args: any = {
|
||||
servicePrincipalId: this.servicePrincipalId,
|
||||
servicePrincipalKey: this.servicePrincipalKey,
|
||||
federatedToken: this.federatedToken,
|
||||
subscriptionId: this.subscriptionId,
|
||||
environment: this.environment,
|
||||
environment: ServicePrincipalLogin.environment,
|
||||
scopeLevel: ServicePrincipalLogin.scopeLevel,
|
||||
allowNoSubscriptionsLogin: this.allowNoSubscriptionsLogin,
|
||||
resourceManagerEndpointUrl: this.resourceManagerEndpointUrl
|
||||
allowNoSubscriptionsLogin: this.allowNoSubscriptionsLogin
|
||||
}
|
||||
const script: string = new ScriptBuilder().getAzPSLoginScript(ServicePrincipalLogin.scheme, this.tenantId, args);
|
||||
await PowerShellToolRunner.init();
|
||||
|
||||
@@ -3,6 +3,7 @@ import * as exec from '@actions/exec';
|
||||
|
||||
export default class PowerShellToolRunner {
|
||||
static psPath: string;
|
||||
|
||||
static async init() {
|
||||
if(!PowerShellToolRunner.psPath) {
|
||||
PowerShellToolRunner.psPath = await io.which("pwsh", true);
|
||||
@@ -10,7 +11,6 @@ export default class PowerShellToolRunner {
|
||||
}
|
||||
|
||||
static async executePowerShellScriptBlock(scriptBlock: string, options: any = {}) {
|
||||
//Options for error handling
|
||||
await exec.exec(`"${PowerShellToolRunner.psPath}" -Command`, [scriptBlock], options)
|
||||
}
|
||||
}
|
||||
@@ -8,28 +8,14 @@ export default class ScriptBuilder {
|
||||
getAzPSLoginScript(scheme: string, tenantId: string, args: any): string {
|
||||
let command = `Clear-AzContext -Scope Process;
|
||||
Clear-AzContext -Scope CurrentUser -Force -ErrorAction SilentlyContinue;`;
|
||||
|
||||
if (scheme === Constants.ServicePrincipal) {
|
||||
|
||||
if (args.environment.toLowerCase() == "azurestack") {
|
||||
command += `Add-AzEnvironment -Name ${args.environment} -ARMEndpoint ${args.resourceManagerEndpointUrl} | out-null;`;
|
||||
}
|
||||
// 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
|
||||
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.scopeLevel === Constants.Subscription && !args.allowNoSubscriptionsLogin) {
|
||||
command += `Set-AzContext -SubscriptionId '${args.subscriptionId}' -TenantId '${tenantId}' | out-null;`;
|
||||
}
|
||||
}
|
||||
|
||||
this.script += `try {
|
||||
$ErrorActionPreference = "Stop"
|
||||
$WarningPreference = "SilentlyContinue"
|
||||
@@ -41,7 +27,6 @@ export default class ScriptBuilder {
|
||||
$output['${Constants.Error}'] = $_.exception.Message
|
||||
}
|
||||
return ConvertTo-Json $output`;
|
||||
|
||||
core.debug(`Azure PowerShell Login Script: ${this.script}`);
|
||||
return this.script;
|
||||
}
|
||||
@@ -63,5 +48,4 @@ export default class ScriptBuilder {
|
||||
core.debug(`GetLatestModuleScript: ${this.script}`);
|
||||
return this.script;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
320
src/main.ts
320
src/main.ts
@@ -1,230 +1,92 @@
|
||||
import * as core from '@actions/core';
|
||||
import * as exec from '@actions/exec';
|
||||
import { ExecOptions } from '@actions/exec/lib/interfaces';
|
||||
import * as io from '@actions/io';
|
||||
import { FormatType, SecretParser } from 'actions-secret-parser';
|
||||
import { ServicePrincipalLogin } from './PowerShell/ServicePrincipalLogin';
|
||||
|
||||
var azPath: string;
|
||||
var prefix = !!process.env.AZURE_HTTP_USER_AGENT ? `${process.env.AZURE_HTTP_USER_AGENT}` : "";
|
||||
var azPSHostEnv = !!process.env.AZUREPS_HOST_ENVIRONMENT ? `${process.env.AZUREPS_HOST_ENVIRONMENT}` : "";
|
||||
|
||||
async function main() {
|
||||
try {
|
||||
//Options for error handling
|
||||
let commandStdErr = false;
|
||||
const loginOptions: ExecOptions = {
|
||||
silent: true,
|
||||
ignoreReturnCode: true,
|
||||
failOnStdErr: true,
|
||||
listeners: {
|
||||
stderr: (data: Buffer) => {
|
||||
let error = data.toString();
|
||||
//removing the keyword 'ERROR' to avoid duplicates while throwing error
|
||||
if (error.toLowerCase().startsWith('error')) {
|
||||
error = error.slice(5);
|
||||
}
|
||||
// printing error
|
||||
if (error && error.trim().length !== 0) {
|
||||
commandStdErr = true;
|
||||
core.error(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Set user agent variable
|
||||
var isAzCLISuccess = false;
|
||||
let usrAgentRepo = `${process.env.GITHUB_REPOSITORY}`;
|
||||
let actionName = 'AzureLogin';
|
||||
let userAgentString = (!!prefix ? `${prefix}+` : '') + `GITHUBACTIONS/${actionName}@v1_${usrAgentRepo}`;
|
||||
let azurePSHostEnv = (!!azPSHostEnv ? `${azPSHostEnv}+` : '') + `GITHUBACTIONS/${actionName}@v1_${usrAgentRepo}`;
|
||||
core.exportVariable('AZURE_HTTP_USER_AGENT', userAgentString);
|
||||
core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azurePSHostEnv);
|
||||
|
||||
azPath = await io.which("az", true);
|
||||
core.debug(`az cli version used: ${azPath}`);
|
||||
let azureSupportedCloudName = new Set([
|
||||
"azureusgovernment",
|
||||
"azurechinacloud",
|
||||
"azuregermancloud",
|
||||
"azurecloud",
|
||||
"azurestack"]);
|
||||
|
||||
let output: string = "";
|
||||
const execOptions: any = {
|
||||
listeners: {
|
||||
stdout: (data: Buffer) => {
|
||||
output += data.toString();
|
||||
}
|
||||
}
|
||||
};
|
||||
await executeAzCliCommand("--version", true, execOptions);
|
||||
core.debug(`az cli version used:\n${output}`);
|
||||
|
||||
let creds = core.getInput('creds', { required: false });
|
||||
let secrets = creds ? new SecretParser(creds, FormatType.JSON) : null;
|
||||
let environment = core.getInput("environment").toLowerCase();
|
||||
const enableAzPSSession = core.getInput('enable-AzPSSession').toLowerCase() === "true";
|
||||
const allowNoSubscriptionsLogin = core.getInput('allow-no-subscriptions').toLowerCase() === "true";
|
||||
|
||||
//Check for the credentials in individual parameters in the workflow.
|
||||
var servicePrincipalId = core.getInput('client-id', { required: false });
|
||||
var servicePrincipalKey = null;
|
||||
var tenantId = core.getInput('tenant-id', { required: false });
|
||||
var subscriptionId = core.getInput('subscription-id', { required: false });
|
||||
var resourceManagerEndpointUrl = "https://management.azure.com/";
|
||||
var enableOIDC = true;
|
||||
var federatedToken = null;
|
||||
|
||||
// If any of the individual credentials (clent_id, tenat_id, subscription_id) is present.
|
||||
if (servicePrincipalId || tenantId || subscriptionId) {
|
||||
|
||||
//If few of the individual credentials (clent_id, tenat_id, subscription_id) are missing in action inputs.
|
||||
if (!(servicePrincipalId && tenantId && (subscriptionId || allowNoSubscriptionsLogin)))
|
||||
throw new Error("Few credentials are missing. ClientId, tenantId are mandatory. SubscriptionId is also mandatory if allow-no-subscriptions is not set.");
|
||||
}
|
||||
else {
|
||||
if (creds) {
|
||||
core.debug('using creds JSON...');
|
||||
enableOIDC = false;
|
||||
servicePrincipalId = secrets.getSecret("$.clientId", true);
|
||||
servicePrincipalKey = secrets.getSecret("$.clientSecret", true);
|
||||
tenantId = secrets.getSecret("$.tenantId", true);
|
||||
subscriptionId = secrets.getSecret("$.subscriptionId", true);
|
||||
resourceManagerEndpointUrl = secrets.getSecret("$.resourceManagerEndpointUrl", false);
|
||||
}
|
||||
else {
|
||||
throw new Error("Credentials are not passed for Login action.");
|
||||
}
|
||||
}
|
||||
//generic checks
|
||||
//servicePrincipalKey is only required in non-oidc scenario.
|
||||
if (!servicePrincipalId || !tenantId || !(servicePrincipalKey || enableOIDC)) {
|
||||
throw new Error("Not all values are present in the credentials. Ensure clientId, clientSecret and tenantId are supplied.");
|
||||
}
|
||||
if (!subscriptionId && !allowNoSubscriptionsLogin) {
|
||||
throw new Error("Not all values are present in the credentials. Ensure subscriptionId is supplied.");
|
||||
}
|
||||
if (!azureSupportedCloudName.has(environment)) {
|
||||
throw new Error("Unsupported value for environment is passed.The list of supported values for environment are ‘azureusgovernment', ‘azurechinacloud’, ‘azuregermancloud’, ‘azurecloud’ or ’azurestack’");
|
||||
}
|
||||
|
||||
// OIDC specific checks
|
||||
if (enableOIDC) {
|
||||
console.log('Using OIDC authentication...')
|
||||
//generating ID-token
|
||||
let audience = core.getInput('audience', { required: false });
|
||||
federatedToken = await core.getIDToken(audience);
|
||||
if (!!federatedToken) {
|
||||
if (environment != "azurecloud")
|
||||
throw new Error(`Your current environment - "${environment}" is not supported for OIDC login.`);
|
||||
}
|
||||
else {
|
||||
throw new Error("Could not get ID token for authentication.");
|
||||
}
|
||||
}
|
||||
|
||||
// Attempting Az cli login
|
||||
if (environment == "azurestack") {
|
||||
if (!resourceManagerEndpointUrl) {
|
||||
throw new Error("resourceManagerEndpointUrl is a required parameter when environment is defined.");
|
||||
}
|
||||
|
||||
console.log(`Unregistering cloud: "${environment}" first if it exists`);
|
||||
try {
|
||||
await executeAzCliCommand(`cloud set -n AzureCloud`, true);
|
||||
await executeAzCliCommand(`cloud unregister -n "${environment}"`, false);
|
||||
}
|
||||
catch (error) {
|
||||
console.log(`Ignore cloud not registered error: "${error}"`);
|
||||
}
|
||||
|
||||
console.log(`Registering cloud: "${environment}" with ARM endpoint: "${resourceManagerEndpointUrl}"`);
|
||||
try {
|
||||
let baseUri = resourceManagerEndpointUrl;
|
||||
if (baseUri.endsWith('/')) {
|
||||
baseUri = baseUri.substring(0, baseUri.length - 1); // need to remove trailing / from resourceManagerEndpointUrl to correctly derive suffixes below
|
||||
}
|
||||
let suffixKeyvault = ".vault" + baseUri.substring(baseUri.indexOf('.')); // keyvault suffix starts with .
|
||||
let suffixStorage = baseUri.substring(baseUri.indexOf('.') + 1); // storage suffix starts without .
|
||||
let profileVersion = "2019-03-01-hybrid";
|
||||
await executeAzCliCommand(`cloud register -n "${environment}" --endpoint-resource-manager "${resourceManagerEndpointUrl}" --suffix-keyvault-dns "${suffixKeyvault}" --suffix-storage-endpoint "${suffixStorage}" --profile "${profileVersion}"`, false);
|
||||
}
|
||||
catch (error) {
|
||||
core.error(`Error while trying to register cloud "${environment}": "${error}"`);
|
||||
}
|
||||
|
||||
console.log(`Done registering cloud: "${environment}"`)
|
||||
}
|
||||
|
||||
await executeAzCliCommand(`cloud set -n "${environment}"`, false);
|
||||
console.log(`Done setting cloud: "${environment}"`);
|
||||
|
||||
// Attempting Az cli login
|
||||
var commonArgs = ["--service-principal",
|
||||
"-u", servicePrincipalId,
|
||||
"--tenant", tenantId
|
||||
];
|
||||
if (allowNoSubscriptionsLogin) {
|
||||
commonArgs = commonArgs.concat("--allow-no-subscriptions");
|
||||
}
|
||||
if (enableOIDC) {
|
||||
commonArgs = commonArgs.concat("--federated-token", federatedToken);
|
||||
}
|
||||
else {
|
||||
commonArgs = commonArgs.concat("-p", servicePrincipalKey);
|
||||
}
|
||||
await executeAzCliCommand(`login`, true, loginOptions, commonArgs);
|
||||
|
||||
if (!allowNoSubscriptionsLogin) {
|
||||
var args = [
|
||||
"--subscription",
|
||||
subscriptionId
|
||||
];
|
||||
await executeAzCliCommand(`account set`, true, loginOptions, args);
|
||||
}
|
||||
isAzCLISuccess = true;
|
||||
if (enableAzPSSession) {
|
||||
// Attempting Az PS login
|
||||
console.log(`Running Azure PS Login`);
|
||||
var spnlogin: ServicePrincipalLogin;
|
||||
|
||||
spnlogin = new ServicePrincipalLogin(
|
||||
servicePrincipalId,
|
||||
servicePrincipalKey,
|
||||
federatedToken,
|
||||
tenantId,
|
||||
subscriptionId,
|
||||
allowNoSubscriptionsLogin,
|
||||
environment,
|
||||
resourceManagerEndpointUrl);
|
||||
await spnlogin.initialize();
|
||||
await spnlogin.login();
|
||||
}
|
||||
|
||||
console.log("Login successful.");
|
||||
}
|
||||
catch (error) {
|
||||
if (!isAzCLISuccess) {
|
||||
core.setFailed("Az CLI Login failed. Please check the credentials. For more information refer https://aka.ms/create-secrets-for-GitHub-workflows");
|
||||
}
|
||||
else {
|
||||
core.setFailed(`Azure PowerShell Login failed. Please check the credentials. For more information refer https://aka.ms/create-secrets-for-GitHub-workflows"`);
|
||||
}
|
||||
}
|
||||
finally {
|
||||
// Reset AZURE_HTTP_USER_AGENT
|
||||
core.exportVariable('AZURE_HTTP_USER_AGENT', prefix);
|
||||
core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azPSHostEnv);
|
||||
}
|
||||
}
|
||||
|
||||
async function executeAzCliCommand(
|
||||
command: string,
|
||||
silent?: boolean,
|
||||
execOptions: any = {},
|
||||
args: any = []) {
|
||||
execOptions.silent = !!silent;
|
||||
await exec.exec(`"${azPath}" ${command}`, args, execOptions);
|
||||
}
|
||||
import * as core from '@actions/core';
|
||||
import * as exec from '@actions/exec';
|
||||
import * as io from '@actions/io';
|
||||
|
||||
import { FormatType, SecretParser } from 'actions-secret-parser';
|
||||
import { ServicePrincipalLogin } from './PowerShell/ServicePrincipalLogin';
|
||||
|
||||
var azPath: string;
|
||||
var prefix = !!process.env.AZURE_HTTP_USER_AGENT ? `${process.env.AZURE_HTTP_USER_AGENT}` : "";
|
||||
var azPSHostEnv = !!process.env.AZUREPS_HOST_ENVIRONMENT ? `${process.env.AZUREPS_HOST_ENVIRONMENT}` : "";
|
||||
|
||||
async function main() {
|
||||
try {
|
||||
// Set user agent variable
|
||||
var isAzCLISuccess = false;
|
||||
let usrAgentRepo = `${process.env.GITHUB_REPOSITORY}`;
|
||||
let actionName = 'AzureLogin';
|
||||
let userAgentString = (!!prefix ? `${prefix}+` : '') + `GITHUBACTIONS/${actionName}@v1_${usrAgentRepo}`;
|
||||
let azurePSHostEnv = (!!azPSHostEnv ? `${azPSHostEnv}+` : '') + `GITHUBACTIONS/${actionName}@v1_${usrAgentRepo}`;
|
||||
core.exportVariable('AZURE_HTTP_USER_AGENT', userAgentString);
|
||||
core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azurePSHostEnv);
|
||||
|
||||
azPath = await io.which("az", true);
|
||||
let output: string = "";
|
||||
const options: any = {
|
||||
listeners: {
|
||||
stdout: (data: Buffer) => {
|
||||
output += data.toString();
|
||||
}
|
||||
}
|
||||
};
|
||||
await executeAzCliCommand("--version", true, options);
|
||||
core.debug(`az cli version used:\n${output}`);
|
||||
|
||||
let creds = core.getInput('creds', { required: true });
|
||||
let secrets = new SecretParser(creds, FormatType.JSON);
|
||||
let servicePrincipalId = secrets.getSecret("$.clientId", false);
|
||||
let servicePrincipalKey = secrets.getSecret("$.clientSecret", true);
|
||||
let tenantId = secrets.getSecret("$.tenantId", false);
|
||||
let subscriptionId = secrets.getSecret("$.subscriptionId", false);
|
||||
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) {
|
||||
await executeAzCliCommand(`login --allow-no-subscriptions --service-principal -u "${servicePrincipalId}" -p "${servicePrincipalKey}" --tenant "${tenantId}"`, true);
|
||||
}
|
||||
else {
|
||||
await executeAzCliCommand(`login --service-principal -u "${servicePrincipalId}" -p "${servicePrincipalKey}" --tenant "${tenantId}"`, true);
|
||||
await executeAzCliCommand(`account set --subscription "${subscriptionId}"`, true);
|
||||
}
|
||||
isAzCLISuccess = true;
|
||||
if (enableAzPSSession) {
|
||||
// Attempting Az PS login
|
||||
console.log(`Running Azure PS Login`);
|
||||
const spnlogin: ServicePrincipalLogin = new ServicePrincipalLogin(servicePrincipalId, servicePrincipalKey, tenantId, subscriptionId, allowNoSubscriptionsLogin);
|
||||
await spnlogin.initialize();
|
||||
await spnlogin.login();
|
||||
}
|
||||
console.log("Login successful.");
|
||||
} catch (error) {
|
||||
if (!isAzCLISuccess) {
|
||||
core.error("Az CLI Login failed. Please check the credentials. For more information refer https://aka.ms/create-secrets-for-GitHub-workflows");
|
||||
} else {
|
||||
core.error(`Azure PowerShell Login failed. Please check the credentials. For more information refer https://aka.ms/create-secrets-for-GitHub-workflows"`);
|
||||
}
|
||||
core.setFailed(error);
|
||||
} finally {
|
||||
// Reset AZURE_HTTP_USER_AGENT
|
||||
core.exportVariable('AZURE_HTTP_USER_AGENT', prefix);
|
||||
core.exportVariable('AZUREPS_HOST_ENVIRONMENT', azPSHostEnv);
|
||||
}
|
||||
}
|
||||
|
||||
async function executeAzCliCommand(command: string, silent?: boolean, options: any = {}) {
|
||||
options.silent = !!silent;
|
||||
try {
|
||||
await exec.exec(`"${azPath}" ${command}`, [], options);
|
||||
}
|
||||
catch(error) {
|
||||
throw new Error(error);
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
Reference in New Issue
Block a user