Skip to content

Latest commit

 

History

History
429 lines (299 loc) · 20.3 KB

connect-from-azure.md

File metadata and controls

429 lines (299 loc) · 20.3 KB
title description author ms.author ms.topic ms.service ms.date ms.custom
Connect GitHub and Azure
Resources to connect to GitHub from Azure and other services
N-Usha
ushan
reference
azure
11/30/2021
github-actions-azure, devx-track-azurecli

Use GitHub Actions to connect to Azure

Learn how to use Azure login with either Azure PowerShell or Azure CLI to interact with your Azure resources.

To use Azure PowerShell or Azure CLI in a GitHub Actions workflow, you need to first log in with the Azure login action.

The Azure login action supports two different ways of authenticating with Azure:

By default, the login action logs in with the Azure CLI and sets up the GitHub action runner environment for Azure CLI. You can use Azure PowerShell with enable-AzPSSession property of the Azure login action. This sets up the GitHub action runner environment with the Azure PowerShell module.

You can use Azure login to connect to public or sovereign clouds including Azure Government and Azure Stack Hub.

Use the Azure login action with OpenID Connect

To set up an Azure Login with OpenID Connect and use it in a GitHub Actions workflow, you'll need:

  • An Azure Active Directory application, with a service principal that has contributor access to your subscription
  • An Azure Active Directory application configured with a federated credential to trust tokens issued by GitHub Actions to your GitHub repository. You can configure this in the Azure portal or with Microsoft Graph REST APIs
  • A GitHub Actions workflow that requests GitHub issue tokens to the workflow, and uses the Azure login action

Create an Azure Active Directory application and service principal

You'll need to create an Azure Active Directory application and service principal and then assign a role on your subscription to your application so that your workflow has access to your subscription.

  1. If you do not have an existing application, register a new Azure Active Directory application and service principal that can access resources. As part of this process, make sure to:

    • Register your application with Azure AD and create a service principal
    • Assign a role to the application
  2. Open App registrations in Azure portal and find your application. Copy the values for Application (client) ID and Directory (tenant) ID to use in your GitHub Actions workflow.

  3. Open Subscriptions in Azure portal and find your subscription. Copy the Subscription ID.

  1. Create the Azure Active Directory application.

    az ad app create --display-name myApp
    

    This command will output JSON with an appId that is your client-id. The objectId is APPLICATION-OBJECT-ID and it will be used for creating federated credentials with Graph API calls.

  2. Create a service principal. Replace the $appID with the appId from your JSON output. This command generates JSON output with a different objectId will be used in the next step. The new objectId is the assignee-object-id.

     az ad sp create --id $appId
    
  3. Create a new role assignment by subscription and object. By default, the role assignment will be tied to your default subscription. Replace $subscriptionId with your subscription ID, $resourceGroupName with your resource group name, and $assigneeObjectId with generated assignee-object-id (the newly created service principal object id).

    az role assignment create --role contributor --subscription $subscriptionId --assignee-object-id  $assigneeObjectId --assignee-principal-type ServicePrincipal --scope /subscriptions/$subscriptionId/resourceGroups/$resourceGroupName
    
  4. Copy the values for clientId, subscriptionId, and tenantId to use later in your GitHub Actions workflow.

  1. Create the Azure Active Directory application.

    New-AzADApplication -DisplayName myApp
    

    This command will output the AppId property that is your ClientId. The Id property is APPLICATION-OBJECT-ID and it will be used for creating federated credentials with Graph API calls.

  2. Create a service principal. Replace the $clientId with the AppId from your output. This command generates output with a different Id and will be used in the next step. The new Id is the ObjectId.

    $clientId = (Get-AzADApplication -DisplayName myApp).AppId
    New-AzADServicePrincipal -ApplicationId $clientId
    
  3. Create a new role assignment. Beginning with Az PowerShell module version 7.x, New-AzADServicePrincipal no longer assigns the Contributor role to the service principal by default. Replace $resourceGroupName with your resource group name, and $objectId with generated Id.

    $objectId = (Get-AzADServicePrincipal -DisplayName myApp).Id
    New-AzRoleAssignment -ObjectId $objectId -RoleDefinitionName Contributor -ResourceGroupName $resourceGroupName
    
  4. Get the values for clientId, subscriptionId, and tenantId to use later in your GitHub Actions workflow.

    $clientId = (Get-AzADApplication -DisplayName myApp).AppId
    $subscriptionId = (Get-AzContext).Subscription.Id
    $tenantId = (Get-AzContext).Subscription.TenantId
    

Add federated credentials

You can add federated credentials in the Azure portal or with the Microsoft Graph REST API.

  1. Go to App registrations in the Azure portal and open the app you want to configure.
  2. Within the app, go to Certificates and secrets.
    :::image type="content" source="media/federated-certificates-secrets.png" alt-text="Select Certificates & secrets.":::
  3. In the Federated credentials tab, select Add credential. :::image type="content" source="media/add-federated-credential.png" alt-text="Add the federated credential":::
  4. Select the credential scenario GitHub Actions deploying Azure resources. Generate your credential by entering your credential details.
Field Description Example
Organization Your GitHub organization name or GitHub username. contoso
Repository Your GitHub Repository name. contoso-app
Entity type The filter used to scope the OIDC requests from GitHub workflows. This field is used to generate the subject claim. Environment, Branch, Pull request, Tag
GitHub name The name of the environment, branch, or tag. main
Name Identifier for the federated credential. contoso-deploy

For a more detailed overview, see Configure an app to trust a GitHub repo.

Run the following command to create a new federated identity credential for your Azure Active Directory application.

  • Replace APPLICATION-OBJECT-ID with the objectId (generated while creating app) for your Azure Active Directory application.
  • Set a value for CREDENTIAL-NAME to reference later.
  • Set the subject. The value of this is defined by GitHub depending on your workflow:
    • Jobs in your GitHub Actions environment: repo:< Organization/Repository >:environment:< Name >
    • For Jobs not tied to an environment, include the ref path for branch/tag based on the ref path used for triggering the workflow: repo:< Organization/Repository >:ref:< ref path>. For example, repo:n-username/ node_express:ref:refs/heads/my-branch or repo:n-username/ node_express:ref:refs/tags/my-tag.
    • For workflows triggered by a pull request event: repo:< Organization/Repository >:pull_request.
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:organization/repository:environment:Production","description":"Testing","audiences":["api://AzureADTokenExchange"]}' 

For a more detailed overview, see Configure an app to trust a GitHub repo.

Run the following command to create a new federated identity credential for your Azure Active Directory application.

  • Replace APPLICATION-OBJECT-ID with the Id (generated while creating app) for your Azure Active Directory application.
  • Set a value for CREDENTIAL-NAME to reference later.
  • Set the subject. The value of this is defined by GitHub depending on your workflow:
    • Jobs in your GitHub Actions environment: repo:< Organization/Repository >:environment:< Name >
    • For Jobs not tied to an environment, include the ref path for branch/tag based on the ref path used for triggering the workflow: repo:< Organization/Repository >:ref:< ref path>. For example, repo:n-username/ node_express:ref:refs/heads/my-branch or repo:n-username/ node_express:ref:refs/tags/my-tag.
    • For workflows triggered by a pull request event: repo:< Organization/Repository >:pull_request.
Invoke-AzRestMethod -Method POST -Uri 'https://graph.microsoft.com/beta/applications/<APPLICATION-OBJECT-ID>/federatedIdentityCredentials' -Payload  '{"name":"<CREDENTIAL-NAME>","issuer":"https://token.actions.githubusercontent.com","subject":"repo:organization/repository:environment:Production","description":"Testing","audiences":["api://AzureADTokenExchange"]}'

For a more detailed overview, see Configure an app to trust a GitHub repo.


Create GitHub secrets

You need to provide your application's Client ID, Tenant ID and Subscription ID to the login action. These values can either be provided directly in the workflow or can be stored in GitHub secrets and referenced in your workflow. Saving the values as GitHub secrets is the more secure option.

  1. Open your GitHub repository and go to Settings.

    :::image type="content" source="media/github-repo-settings.png" alt-text="Select Settings in the navigation":::

  2. Select Secrets and then New Secret.

    :::image type="content" source="media/select-secrets.png" alt-text="Choose to add a secret":::

  3. Create secrets for AZURE_CLIENT_ID, AZURE_TENANT_ID, and AZURE_SUBSCRIPTION_ID. Use these values from your Azure Active Directory application for your GitHub secrets:

    GitHub Secret Azure Active Directory Application
    AZURE_CLIENT_ID Application (client) ID
    AZURE_TENANT_ID Directory (tenant) ID
    AZURE_SUBSCRIPTION_ID Subscription ID
  4. Save each secret by selecting Add secret.

Set up Azure Login with OpenID Connect authentication

Your GitHub Actions workflow uses OpenID Connect to authenticate with Azure. To learn more about this interaction, see the GitHub Actions documentation.

In this example, you'll use OpenID Connect Azure CLI to authenticate with Azure with the Azure login action. The example uses GitHub secrets for the client-id, tenant-id, and subscription-id values. You can also pass these values directly in the login action.

The Azure login action includes an optional audience input parameter that defaults to api://AzureADTokenExchange. You can update this parameter for custom audience values.

This workflow authenticates with OpenID Connect and uses Azure CLI to get the details of the connected subscription and list resource group.

name: Run Azure Login with OpenID Connect
on: [push]

permissions:
      id-token: write
      contents: read
      
jobs: 
  build-and-deploy:
    runs-on: ubuntu-latest
    steps:
    - name: 'Az CLI login'
      uses: azure/login@v1
      with:
          client-id: ${{ secrets.AZURE_CLIENT_ID }}
          tenant-id: ${{ secrets.AZURE_TENANT_ID }}
          subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
  
    - name: 'Run Azure CLI commands'
      run: |
          az account show
          az group list
          pwd 

This workflow authenticates with OpenID Connect and uses PowerShell to output a list of resource groups tied to the connected Azure subscription.

name: Run Azure Login with OpenID Connect and PowerShell
on: [push]

permissions:
      id-token: write
      contents: read
      
jobs: 
  Windows-latest:
      runs-on: windows-latest
      steps:
        - name: OIDC Login to Azure Public Cloud with AzPowershell (enableAzPSSession true)
          uses: azure/login@v1
          with:
            client-id: ${{ secrets.AZURE_CLIENT_ID }}
            tenant-id: ${{ secrets.AZURE_TENANT_ID }}
            subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }} 
            enable-AzPSSession: true

        - name: 'Get resource group with PowerShell action'
          uses: azure/powershell@v1
          with:
             inlineScript: |
               Get-AzResourceGroup
             azPSVersion: "latest"

Verify successful Azure Login with OpenID

Open the Az CLI login action and verify that it ran successfully. You should see the message Login successful. If your login is unsuccessful, you'll see the message Az CLI Login failed..

:::image type="content" source="media/github-actions-successful-login.png" alt-text="GitHub Actions Azure Login successful.":::

Use the Azure login action with a service principal secret

To use Azure login with a service principal, you first need to add your Azure service principal as a secret to your GitHub repository.

Create a service principal and add it as a GitHub secret

In this example, you will create a secret named AZURE_CREDENTIALS that you can use to authenticate with Azure.

  1. Open Azure Cloud Shell in the Azure portal or Azure CLI locally.

    [!NOTE] If you are using Azure Stack Hub, you'll need to set your SQL Management endpoint to not supported. az cloud update -n {environmentName} --endpoint-sql-management https://notsupported

  2. Create a new service principal in the Azure portal for your app. The service principal must be assigned the Contributor role.

        az ad sp create-for-rbac --name "myApp" --role contributor \
                                    --scopes /subscriptions/{subscription-id}/resourceGroups/{resource-group} \
                                    --sdk-auth
    
  3. Copy the JSON object for your service principal.

    {
        "clientId": "<GUID>",
        "clientSecret": "<GUID>",
        "subscriptionId": "<GUID>",
        "tenantId": "<GUID>",
        (...)
    }
  4. Open your GitHub repository and go to Settings.

    :::image type="content" source="media/github-repo-settings.png" alt-text="Select Settings in the navigation":::

  5. Select Secrets and then New Secret.

    :::image type="content" source="media/select-secrets.png" alt-text="Choose to add a secret":::

  6. Paste in your JSON object for your service principal with the name AZURE_CREDENTIALS.

    :::image type="content" source="media/azure-secret-add.png" alt-text="Add a secret in GitHub":::

  7. Save by selecting Add secret.

Use the Azure login action

Use the service principal secret with the Azure Login action to authenticate to Azure.

In this workflow, you authenticate using the Azure login action with the service principal details stored in secrets.AZURE_CREDENTIALS. Then, you run an Azure CLI action. For more information about referencing GitHub secrets in a workflow file, see Using encrypted secrets in a workflow in GitHub Docs.

Once you have a working Azure login step, you can use the Azure PowerShell or Azure CLI actions. You can also use other Azure actions, like Azure webapp deploy and Azure functions.

on: [push]

name: AzureLoginSample

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Log in with Azure
        uses: azure/login@v1
        with:
          creds: '${{ secrets.AZURE_CREDENTIALS }}'

Use the Azure PowerShell action

In this example, you log in with the Azure Login action and then retrieve a resource group with the Azure PowerShell action.

on: [push]

name: AzureLoginSample

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Log in with Azure
        uses: azure/login@v1
        with:
          creds: '${{ secrets.AZURE_CREDENTIALS }}'
          enable-AzPSSession: true
      - name: Azure PowerShell Action
        uses: Azure/powershell@v1
        with:
          inlineScript: Get-AzResourceGroup -Name "< YOUR RESOURCE GROUP >"
          azPSVersion: "latest"

Use the Azure CLI action

In this example, you log in with the Azure Login action and then retrieve a resource group with the Azure CLI action.

on: [push]

name: AzureLoginSample

jobs:
build-and-deploy:
    runs-on: ubuntu-latest
    steps:

    - name: Log in with Azure
        uses: azure/login@v1
        with:
        creds: ${{ secrets.AZURE_CREDENTIALS }}

    - name: Azure CLI script
        uses: azure/CLI@v1
        with:
        azcliversion: 2.0.72
        inlineScript: |
            az account show
            az storage -h

Connect to Azure Government and Azure Stack Hub clouds

To log in to 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 connects to the Azure Public Cloud.

   - name: Login to Azure US Gov Cloud with CLI
     uses: azure/login@v1
        with:
          creds: ${{ secrets.AZURE_US_GOV_CREDENTIALS }}
          environment: 'AzureUSGovernment'
          enable-AzPSSession: false
   - name: Login to Azure US Gov Cloud with Az Powershell
      uses: azure/login@v1
        with:
          creds: ${{ secrets.AZURE_US_GOV_CREDENTIALS }}
          environment: 'AzureUSGovernment'
          enable-AzPSSession: true

Connect with other Azure services

The following articles provide details on connecting to GitHub from Azure and other services.

Azure Active Directory

Power BI

Connectors

Azure Databricks

[!div class="nextstepaction"] Deploy apps from GitHub to Azure