Set-AzureRmContext error when executed within an Azure Automation Runbook Set-AzureRmContext error when executed within an Azure Automation Runbook powershell powershell

Set-AzureRmContext error when executed within an Azure Automation Runbook


I had the same issue a few weeks ago and what worked was to first login to Azure account (which I think you already did) using:

Login-AzureRmAccount

Then get the subscription ID from Azure and use select the subscription using the ID instead of the name as follows:

Select-AzureRmSubscription -SubscriptionId {insert-subscription-id}


Below is the code that worked for me (regular dc regions). If it doesn't work, go to the Automation Account >> Modules >> Update Azure Modules.

$ClientSecret = ""$ApplicationId = ""$SubscriptionId = ""#New PSCredential Object$secpasswd = ConvertTo-SecureString $ClientSecret -AsPlainText -Force$mycreds = New-Object System.Management.Automation.PSCredential ($ApplicationId , $secpasswd)#Login to subscriptionLogin-AzureRmAccount -Credential $mycreds -SubscriptionId $SubscriptionId#Export DatabaseNew-AzureRmSqlDatabaseExport -ResourceGroupName "<RG>" -ServerName "<SQLSERVERNAME>" -DatabaseName "<DATABASENAME>" -StorageKeyType "StorageAccessKey" -StorageKey "<STRKEY>" -StorageUri "<URITOFILE>" -AdministratorLogin "<DBLOGIN>" -AdministratorLoginPassword "<DBPASS>"

Update

Maybe running with a Run As Account can be a workaround for the issue. Create one by navigating to the Azure Automation Account >> Account Settings >> Run As Accounts. Here's an example code.

# Authenticate to Azure with service principal and certificate, and set subscription$connectionAssetName = "AzureRunAsConnection"$conn = Get-AutomationConnection -Name $ConnectionAssetNameAdd-AzureRmAccount -ServicePrincipal -Tenant $conn.TenantID -ApplicationId $conn.ApplicationId -CertificateThumbprint $conn.CertificateThumbprint -ErrorAction Stop | Write-VerboseSet-AzureRmContext -SubscriptionId $conn.SubscriptionId -ErrorAction Stop | Write-Verbose


It looks like this is a known issue and I wasn't able to find a fix for that. But there are two workarounds:

  1. Using a Hybrid Runnbook Worker (mentioned by Walter - MSFT)
  2. Using a RunAsAccount with certificate credentials (mentioned by Bruno Faria)

It is important to specify the -Environment parameter. Otherwise I got the following exception:

Login-AzureRmAccount : AADSTS90038: Confidential Client is not supported in Cross Cloud request.

Here is the code I am using to login to AzureGermanCloud (MCD) from an Azure Runbook hosted in NorthEurope:

$connectionAssetName = "AzureRunAsConnection"$conn = Get-AutomationConnection -Name $ConnectionAssetNameLogin-AzureRmAccount `    -ServicePrincipal `    -CertificateThumbprint $conn.CertificateThumbprint `    -ApplicationId $conn.ApplicationId `    -TenantId $conn.TenantID `    -Environment AzureGermanCloud