Github Action Az Automation PowerShell: Object reference not set to an instance of an object

Kontext Kontext event 2022-12-28 visibility 626
more_vert
Github Action Az Automation PowerShell: Object reference not set to an instance of an object

This article provides solution to fix object null reference exception when invoking Az automation module in GitHub Actions workflows.

Issue context

When using GitHub Actions to run Azure Az automation PowerShell module, error Object reference not set to an instance of an object was thrown out. The workflow is based on standard template:

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

    steps:
      - uses: actions/checkout@v3

      # Login to Azure
      - uses: azure/login@v1
        with:
          client-id: ${{ secrets.AZURE_CLIENT_ID }}
          tenant-id: ${{ secrets.AZURE_TENANT_ID }}
          subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}

      # Deploy runbooks
      - name: Deploy Azure runbooks
        uses: azure/powershell@v1
        with:
          inlineScript: |
            pushd ./scripts/deploy
            ./deploy-automation-runbooks.ps1 -resourceGroupName "${{ secrets.AZURE_RG }}" -automationAccountName "${{ secrets.*** }}"
            popd
          azPSVersion: "latest"

      # Logout
      - name: logout
        run: |
          az logout

About the template

The template has four major steps:

  • Checkout the code from the repository.
  • Login to Azure via OIDC.
  • Run Azure PowerShell scripts using action azure/powershell.
  • Logout.

About the error message

The error message is a common .NET exception when an object is referenced but not initialized. We can add try-catch to your PowerShell script to print out more detailed error messages. 

As the following screenshot shows, the null object is context (IAzureContext). 

20221228133727-image.png

Resolution

The error occurred because the Azure Context is not initialized or enabled even we have successfully logged in using action azure/login.

To fix this issue, we just need to enable PowerShell session when login:

      # Login to Azure
      - 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

Use argument enable-AzPSSession to enable it and the issue will be gone.

More from Kontext
comment Comments
No comments yet.

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts