Azure Runbook - 在上下文中找不到订阅

Azure Runbook - No subscription found in the context

背景:

我正在尝试通过 Azure 上的 Runbooks 设置脚本。我发现不寻常的是,我可以 运行 通过 Azure Powershell Cloud Shell 命令并且它有效。但是,当我尝试通过 Runbook 运行 它时,我收到一个错误(见下文)。

脚本:

$ResourceGroupName = "group"
$ServerName = "serverName"
$DatabaseName = "databaseName"
$StorageKeyType = "StorageAccessKey"
$StorageKey = "storageKey"
$StorageUri = "storageUri"
$AdminLogin = "admin"
$AdminPassword = (ConvertTo-SecureString "12345" -AsPlainText -Force)

New-AzureRmSqlDatabaseExport `
        -AdministratorLogin $AdminLogin `
        -AdministratorLoginPassword $AdminPassword `
        -DatabaseName $DatabaseName `
        -ResourceGroupName $ResourceGroupName `
        -ServerName $ServerName `
        -StorageKey $StorageKey `
        -StorageKeyType $StorageKeyType `
        -StorageUri $StorageUri `

**使用的通用值

错误:

New-AzureRmSqlDatabaseExport : No subscription found in the context.  Please ensure that the credentials you provided 
are authorized to access an Azure subscription, then run Connect-AzureRmAccount to login.
At line:10 char:1
+ New-AzureRmSqlDatabaseExport `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [New-AzureRmSqlDatabaseExport], ApplicationException
    + FullyQualifiedErrorId : Microsoft.Azure.Commands.Sql.ImportExport.Cmdlet.NewAzureSqlDatabaseExport

问题:

我做错了什么?我使用的密码和用户名是在其他地方使用的密码和用户名,并且在我 运行 云 Shell 中的脚本时工作。另外,"No subscription found in the context"是什么意思?

这意味着您需要在执行任何操作之前登录到Azure。 Cloud Shell 会为您处理这些,而 Azure Automation 不会。

https://docs.microsoft.com/en-us/powershell/azure/get-started-azureps?view=azurermps-5.5.0#log-in-to-azure

您可以使用 Azure AD 用户登录、证书登录或服务主体登录。真实账户无法使用,因为它是交互式的。

在 Azure Cloud Shell 中,您已经登录了您的帐户,因此不需要再次登录。但在 Runbook 中,您需要先登录您的帐户。

您可以使用以下代码登录。

$connectionName = "AzureRunAsConnection"
try
{
    # Get the connection "AzureRunAsConnection "
    $servicePrincipalConnection=Get-AutomationConnection -Name $connectionName         

    "Logging in to Azure..."
    Add-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
    }
}

上面代码中,需要用到连接AzureRunAsConnection,Azure默认创建,可以直接使用。

有关此的更多信息,您也可以查看此