首页 > 解决方案 > 在 VSTS Azure Powershell 任务中使用 Set-AzureStorageBlobContent 时出现“无法获取存储上下文”错误

问题描述

我在 Azure (VSTS) 管道中使用 Azure Powershell 任务来尝试将文件上传到 Azure 经典容器。
作为设置 Azure Powershell 任务(版本 3.1.10)的一部分,我将此容器所在的 Azure 经典订阅添加到项目设置\服务连接中: 服务连接

然后我在管道任务中选择该订阅: 选择订阅

当我执行脚本时,日志似乎显示该任务正在设置和选择预期的订阅:
日志

但是,如果我没有显式(重新)创建并将 AzureStorageContext 传递给 Set-AzureStorageBlobContent 函数,则任务将失败并显示:

[error]Could not get the storage context. Please pass in a storage context or set the current storage context.

这是预期的行为吗?
当它看起来已经存在时,有什么办法可以不必重新创建和传递上下文?

例如,是否有一个环境变量可能包含我可以传入的自动创建/选择的上下文?

更新: 我怀疑如果 Select-AzureSubscription在日志中看到的调用使用了 -Current 开关,这将按我的预期工作。但是,由于该命令是自动运行的,无法通过管道任务对其进行配置,因此无法验证。
也许这需要一个功能请求?

脚本摘录:

#Not passing in the context results in the error
Set-AzureStorageBlobContent -File "$file" -Blob "$blobpath/$blah" -Container $blobname -Properties $properties -Force

#Passing in the context works:  
$azureKey = Get-AzureStorageKey "$accountName"
$storagekey = [string]$azureKey.Primary
$context = New-AzureStorageContext "$accountName" -StorageAccountKey $storagekey  
Set-AzureStorageBlobContent -File "$file" -Blob "$blobpath/$blah" -Container $blobname -Properties $properties -Context $context -Force

标签: azurepowershellazure-devops

解决方案


虽然我可能应该删除这个问题(在发现“答案”后),但我想我会在更多调试等之后提供我发现的内容。

TLDR;-- 这主要是我没有理解 Azure 订阅(上下文)与 Azure 存储(上下文)不相关的概念。

这是预期的行为吗?

是的。简单地拥有当前设置的订阅并不意味着存在当前设置的存储上下文。

来了解一下,我们公司在我使用的订阅中有多个存储帐户。
可能是如果订阅只有一个存储帐户,该函数会在不指定上下文的情况下成功吗?也许我稍后会研究。

当它看起来已经存在时,有什么办法可以不必重新创建和传递上下文?

否(可能是因为订阅中有多个存储帐户)。
我将不得不从当前订阅中指定/选择当前存储上下文(就像我在问题的“传递上下文有效”部分中所做的那样)。

我是这样得出结论的:首先
,我验证了实际设置的内容(如果有的话)作为当前的 [订阅] 上下文,然后明确地(重新)设置它。 运行命令仍然失败。 所以,并不是没有设置订阅(因为它是)。

$current = (Get-AzureSubscription -Current).SubscriptionName
Write-Host "current subscription is $current"

$setCurrent = $false
Write-Host "setCurrent is $setCurrent"
$setCurrent = Select-AzureSubscription -Current -SubscriptionName "CDN Subscription" -PassThru
if ($setCurrent)
{
  Write-Host "current set"
  $current = (Get-AzureSubscription -Current).SubscriptionName
  Write-Host "current subscription is $current"
}
else
{
  Write-Host "current not set"
}  

输出_1

然后我恍然大悟,也许“订阅”不等于“存储”。为了验证这一点,我运行了以下命令:

$current = (Get-AzureSubscription -Current).SubscriptionName
Write-Host "current subscription is $current"

$table = Get-AzureStorageAccount | Format-Table -AutoSize -Property @{Label="Name";Expression={$_.StorageAccountName}},"Label","Location" | Out-String
Write-Host "$table"

结果 - 订阅中有 4 个存储帐户。因此,我需要指定我要上传到的帐户

桌子


推荐阅读