-->

Azure automation: Authentication succeeds but no s

2019-08-21 07:46发布

问题:

Having a problem with creating an azure automation runbook that will copy a database on demand; I've created a credential and stored the u/p of the account I use to log into the portal in it. Password was written in notepad and pasted in to ensure correct.

$Cred = Get-AutomationPSCredential -Name 'automationCredential'

Write-Output "UN: $($Cred.Username)"
Write-Output "PW: $($Cred.Password.Length)"

Add-AzureRmAccount -Credential $Cred

Write-Output "Deleting the old $TargetDatabaseName"

Remove-AzureRMSqlDatabase -ResourceGroupName "Default-SQL-NorthEurope" -ServerName $SourceServerName -DatabaseName $TargetDatabaseName -Force

Write-Output "Creating new $TargetDatabaseName with data at time $PointInTime"

New-AzureRmSqlDatabaseCopy `
    -CopyDatabaseName $TargetDatabaseName `
    -DatabaseName $SourceDatabaseName `
    -ResourceGroupName "Default-SQL-NorthEurope" `
    -ServerName $SourceServerName

The debug prints seem to indicate the credentials are correct, but when the add-azurermaccount is carried out, it seems to log in but no subscriptions are returned

Soon after the call to remove the old test db fails with:

Remove-AzureRMSqlDatabase : No subscription found in the context. Please ensure that the credentials you provided are authorized to access an Azure subscription, then run Login-AzureRMAccount to login.

If I do the actions in the command line powershell (the only difference being I call login without parameters; it prompts for creds) then things work out just fine

I found some resources that indicate if the creds are wrong, it authenticates but returns no subscriptions - i've double checked the creds tho and they're accurate

回答1:

In Azure, Microsoft account does not support non-interactive login.
If you want to use script to login Azure in runbook, we can create a service principal to login Azure.

We can use powershell to create Azure service principal, more information about service principal, please refer to this link.


We can use service principal to login Azure powershell, like this:

$subscriptionId="5384xxxx-xxxx-xxxx-xxxx-xxxxe29axxxx"
$tenantid="1fcf418e-66ed-4c99-9449-d8e18bf8737a"
$appid="1498b171-e1ca-451f-9d7a-8ef56a178b89" 
$password="7db814b1-xxxx-4654-xxxx-1d210cb546f9"
$userPassword = ConvertTo-SecureString -String $password -AsPlainText -Force
$userCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $clientid, $userPassword
Add-AzureRmAccount -TenantId $tenantid -ServicePrincipal -SubscriptionId $subscriptionId -Credential $userCredential 

About create service principal, we can use CLI 2.0 to create it, like this:

az login

az account set --subscription "mySubscriptionID"

az group create -n "myResourceGroupName" -l "westus"

az ad sp create-for-rbac --role="Contributor" --scopes="/subscriptions/mySubscriptionID/resourceGroups/myResourceGroupName"