首页 > 解决方案 > 为什么某些 Azure CLI 命令需要 az login

问题描述

在我们的 VSTS 发布管道中,我们想要调用一个 powershell 脚本,为我的一个 Azure Functions 添加一个功能键(使用密钥管理 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

留言:

错误:请运行“az login”来设置帐户。

我们还有其他可用的 azure cli 调用,例如:az cosmosdb 数据库,所以我猜我们的服务原则连接已经到位。这里可能是什么问题?

标签: azurepowershellazure-devopsazure-pipelinesazure-cli

解决方案


似乎我们有一个旧的 powershell 版本,其中包含一个错误,当您创建新的服务连接身份验证时,它会保留旧的服务连接身份验证上下文,我在这种情况下就是这样做的。

因此,我们在构建代理上更新了 powershell,一切顺利!


推荐阅读