使用Azure DevOps Pipeline更新Azure Key Vault密钥时遇az登录错误
问题解决:Azure DevOps管道执行Azure CLI命令提示需登录
你的问题核心是AzurePowerShell@5任务仅自动为PowerShell Az模块完成了Service Principal身份验证,但脚本里使用的是Azure CLI(az开头)命令,这类命令不会自动继承PowerShell的登录上下文,因此会抛出Please run 'az login'的错误。
下面提供两种可行的解决办法:
办法一:在脚本中添加Azure CLI的Service Principal登录步骤
利用AzurePowerShell任务自动注入的环境变量(包含Service Principal的凭据),在执行az命令前手动完成CLI登录:
修改后的内联脚本如下:
$env:path = $env:path + ";C:\Program Files\Git\usr\bin" + ";C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\wbin" Invoke-WebRequest -UseBasicParsing -Uri "https://keyserviceurlgoes.here" -OutFile C:\api-key Set-Location C:\ $data = openssl pkeyutl -decrypt -in api-key -inkey my.key $SecretImport = $data | ConvertFrom-Json $Planned = (get-date $SecretImport.metadata.created_at).ToString("yyyy-MM-dd'T'HH:MM:ss'Z'") $ConfluentAPIKey = "$(secretConfluentApiKey)" $ConfluentAPISecret = "$(secretConfluentApiSecret)" $ValutName = "$(azureKeyVaultName)" # 新增Azure CLI的Service Principal登录步骤 az login --service-principal -u $env:AZURE_CLIENT_ID -p $env:AZURE_CLIENT_SECRET --tenant $env:AZURE_TENANT_ID $CurrentKey = az keyvault secret show --name $ConfluentAPIKey --vault-name $ValutName --query "value" if ($CurrentKey -eq $SecretImport.key) { write-host 'Key is in Active State' } else { az keyvault secret set --vault-name $ValutName --name $ConfluentAPIKey --value $SecretImport.key --expires $Planned az keyvault secret set --vault-name $ValutName --name $ConfluentAPISecret --value $SecretImport.secret --expires $Planned }
办法二:改用PowerShell Az模块命令替代Azure CLI
既然使用的是AzurePowerShell任务,直接适配Az模块命令更省心,无需额外处理登录逻辑:
修改后的内联脚本如下:
$env:path = $env:path + ";C:\Program Files\Git\usr\bin" + ";C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\wbin" Invoke-WebRequest -UseBasicParsing -Uri "https://keyserviceurlgoes.here" -OutFile C:\api-key Set-Location C:\ $data = openssl pkeyutl -decrypt -in api-key -inkey my.key $SecretImport = $data | ConvertFrom-Json $Planned = (get-date $SecretImport.metadata.created_at).ToString("yyyy-MM-dd'T'HH:MM:ss'Z'") $ConfluentAPIKey = "$(secretConfluentApiKey)" $ConfluentAPISecret = "$(secretConfluentApiSecret)" $ValutName = "$(azureKeyVaultName)" # 用Az模块命令替换Azure CLI命令 $CurrentKey = Get-AzKeyVaultSecret -VaultName $ValutName -Name $ConfluentAPIKey -AsPlainText if ($CurrentKey -eq $SecretImport.key) { write-host 'Key is in Active State' } else { Set-AzKeyVaultSecret -VaultName $ValutName -Name $ConfluentAPIKey -SecretValue (ConvertTo-SecureString $SecretImport.key -AsPlainText -Force) -Expires $Planned Set-AzKeyVaultSecret -VaultName $ValutName -Name $ConfluentAPISecret -SecretValue (ConvertTo-SecureString $SecretImport.secret -AsPlainText -Force) -Expires $Planned }
额外注意事项
- 确保代理池的Azure VM上已安装对应工具:办法一需要Azure CLI,办法二需要Az PowerShell模块
- 确认你的Service Principal拥有Azure Key Vault的操作权限(如
Key Vault Secrets Officer)
内容的提问来源于stack exchange,提问作者Unknown Coder
相关产品推荐
相关产品推荐

