在我们的 VSTS 发布管道中,我们想要调用一个 powershell 脚本,为我的 Azure Functions 之一添加功能 key (使用 key 管理 REST API)。
我根据这篇文章创建了一个脚本: https://www.markheath.net/post/managing-azure-function-keys
Param(
[string] [Parameter(Mandatory=$true)] $ResourceGroup,
[string] [Parameter(Mandatory=$true)] $AppName,
[string] [Parameter(Mandatory=$true)] $FunctionName,
[string] [Parameter(Mandatory=$true)] $KeyName,
[string] [Parameter(Mandatory=$true)] $KeyValue
)
function getAuthenticationToken([string]$appName, [string]$resourceGroup)
{
$user = az webapp deployment list-publishing-profiles -n $appName -g $resourceGroup `
--query "[?publishMethod=='MSDeploy'].userName" -o tsv
$pass = az webapp deployment list-publishing-profiles -n $appName -g $resourceGroup `
--query "[?publishMethod=='MSDeploy'].userPWD" -o tsv
$pair = "$($user):$($pass)"
$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))
$jwt = Invoke-RestMethod -Uri "https://$appName.scm.azurewebsites.net/api/functions/admin/token" -Headers @{Authorization=("Basic {0}" -f $encodedCreds)} -Method GET
return $jwt
}
function setFunctionKey([string]$appName, [string]$functionName, [string] $keyName, [string]$keyValue, [string]$jwt)
{
$body = (@{
"name" = $keyName
"value" = $keyValue
} | ConvertTo-Json)
#Setting the SecurityProtocol is a workaround for calling Azure APIs, I think?
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
try {
Invoke-RestMethod -Uri "https://$appName.azurewebsites.net/admin/functions/$functionName/keys/$keyName/" `
-Headers @{Authorization=("Bearer $jwt")} `
-Method PUT `
-ContentType "application/json" `
-Body $body
} catch {
$_.Exception | Format-List -Force
}
}
$jwt = getAuthenticationToken $AppName $ResourceGroup
setFunctionKey $AppName $FunctionName $KeyName $KeyValue $jwt
Write-Host "Specified key '$KeyName' has been added to $FunctionName"
在本地工作,但在 VSTS 中运行时,调用时会出现错误
$user = az webapp deployment list-publishing-profiles -n $appName -g $resourceGroup `
--query "[?publishMethod=='MSDeploy'].userName" -o tsv
带有消息:
ERROR: Please run 'az login' to setup account.
我们还有其他可用的 azure cli 调用,例如:az cosmosdb 数据库,所以我猜我们的服务原则连接已就位。这里可能出现什么问题?
最佳答案
似乎我们有一个旧的 powershell 版本,其中包含一个错误,当您创建新的服务连接身份验证时,该错误会保留旧的服务连接身份验证上下文,我在本例中就是这样做的案例。
因此,我们更新了构建代理上的 powershell,一切顺利!
关于azure - 为什么某些 Azure CLI 命令需要 az login,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51960820/