Home > OS >  Set-AzContext authentication inside a runbook run on Hybrid Worker works only a few times, eventuall
Set-AzContext authentication inside a runbook run on Hybrid Worker works only a few times, eventuall

Time:09-29

Instead of using Connect-AzAccount, I'm using a profile saved locally on my Hybrid Worker to authenticate against Azure and loading it each time I run a runbook.

This approach works, but after 2 or 3 successful runs, all the following runbook jobs end up in Suspended state.
Unfortunately, jobs stop working so randomly that I just can't pinpoint a possible cause.

The auth code inside the runbook:

$profile = Import-AzContext -path $path

$subscriptionID = $profile.Context.Subscription.SubscriptionID

Set-AzContext -subscriptionID $subscriptionID

Running Get-AzContext locally confirms that the credentials & context are loaded, but Microsoft-SMA logs show an auth error (407 proxy).

Is there maybe a scope that I should set? Expiration time that I don't know about? Should I maybe clear the context after each job run?

Any input would be appreciated.

CodePudding user response:

Start by running Clear-AzContext at the beginning of your runbook to ensure any inherited contexts are cleared, or Disconnect-AzAccount at the end of your runbook. Per Microsoft:

By default, the Azure contexts are saved for use between PowerShell sessions. It is possible that when a previous runbook on the Hybrid Runbook Worker has been authenticated with Azure, that context persists to the disk in the System PowerShell profile, as per Azure contexts and sign-in credentials | Microsoft Docs. For instance, a runbook with Get-AzVM can return all the VMs in the subscription with no call to Connect-AzAccount, and the user would be able to access Azure resources without having to authenticate within that runbook. You can disable context autosave in Azure PowerShell, as detailed here.

If that doesn't resolve the issue I would enable Progress logging and step through the runbook to identify which part is causing the issue.

  • Related