1

I wish to select a subscription available for my service principle within an Azure Automation PS job. Running the following code locally works fine, but within the automation job, I only get the following error

Provided subscription xxxx-xxxx-xxxx-xxx-xxxx does not exist.

The subscription does exist, and the service principal has access to it when I log onto it locally.

$id = "someid"
$pass = "somepass"

$securePass = $pass | ConvertTo-SecureString -AsPlainText -Force

$cred = new-object -TypeName System.Management.Automation.PsCredential -ArgumentList $id, $securePass

$tenantId = "someID"

Add-AzureRmAccount -Credential $cred -TenantId $tenantId -ServicePrincipal

Select-AzureRmSubscription -SubscriptionId "someID"
Refi
  • 79
  • 11

2 Answers2

0

For using Azure Automation, you should create the Automation account with AzureRunAsConnection enabled. Then from the script you utilize it like this

$connectionName = "AzureRunAsConnection"
try {
    # Get the connection "AzureRunAsConnection "
    $servicePrincipalConnection = Get-AutomationConnection -Name $connectionName
    "Logging in to Azure..."
    Connect-AzureRmAccount `
        -ServicePrincipal `
        -TenantId $servicePrincipalConnection.TenantId `
        -ApplicationId $servicePrincipalConnection.ApplicationId `
        -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
}
catch {
    if (!$servicePrincipalConnection) {
        $ErrorMessage = "Connection $connectionName not found."
        throw $ErrorMessage
    }
    else {
        Write-Error -Message $_.Exception
        throw $_.Exception
    }
}

Hope this helps

HariHaran
  • 3,642
  • 2
  • 16
  • 33
0

Finally, I figured out this issue, after some days.

This issue is already reported here.

It is due to the issue related to Add-AzureRmAccount cmdlets with Service Principal.

There is a workaround to solve this issue, as mentioned by Hariharan

$connectionAssetName = "AzureRunAsConnection"
$conn = Get-AutomationConnection -Name $ConnectionAssetName

Login-AzureRmAccount `
    -ServicePrincipal `
    -CertificateThumbprint $conn.CertificateThumbprint `
    -ApplicationId $conn.ApplicationId `
    -TenantId $conn.TenantID `
    -Environment AzureGermanCloud

Refer this S.O

Jayendran
  • 9,638
  • 8
  • 60
  • 103