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

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

Kontext Kontext 1 659 0.74 index 12/28/2022

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).

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.

azure-bicep devops powershell

Join the Discussion

View or add your thoughts below

Comments