在 azure devops 中使用 azure powershell 内联任务获取 azure 函数密钥并将其放入 keyvault 的脚本

Script to get the azure function key and put it in keyvault using azure powershell inline task in azure devops

我在 Azure DevOps 的 3.1.0 版本的 Azure PowerShell 内联脚本任务中有 运行 下面的命令。

$accountInfo = az account show

$accountInfoObject = $accountInfo | ConvertFrom-Json

$subscriptionId  = $accountInfoObject.id

$resourceGroup = "BZE1ERG01"

$functionName = "BAZE1EFA01"

$functionkeylist = az rest --method post --uri "https://management.azure.com/subscriptions/$subscriptionId/resourceGroups/$resourceGroup/providers/Microsoft.Web/sites/$functionName/host/default/listKeys?api-version=2018-11-01"

$keylistobject = $functionkeylist | ConvertFrom-Json
$functionKey = $keylistobject.functionKeys.default    

$tmpSecret1 = ConvertTo-SecureString $functionKey -AsPlainText -Force

Set-AzKeyVaultSecret -VaultName 'azu-qa-keyvault' -Name functionkeysecret -SecretValue $tmpSecret1

DevOps 屏幕截图

我遇到错误

您收到此消息是因为看起来您使用 az cli 进行的调用未经过身份验证。正在关注 docs

Use this task to run a PowerShell script within an Azure environment. The Azure context is authenticated with the provided Azure Resource Manager service connection.

您应该使用纯 PowerShell Az 模块,或者如果您想使用 az li,请考虑使用 Azure CLI task which will take care of autorization. You can use az keyvault secret set to create/update a secret in KeyVault. Please take a look on documentation 了解更多详细信息。当然,所有 powershell 代码在此任务中都是有效的。

看起来一个人的身份验证不适用于另一个人。您还可以使用以下语法从您的任务登录到 az cli:

az login --service-principal --username <app-id> --password <password> --tenant <tenant-id>

发生上述错误 Please run 'az login' to setup account 是因为您在 azure powershell 任务中 运行ning azure cli 命令(例如 az account show)。

因此,如果您想在 Azure powershell 任务中 运行 azure cli 命令。您需要 运行 az login 才能登录。例如。 az login --service-principal -u <app-url> -p <password-or-cert> --tenant <tenant>。如果您没有服务主体。您可以按照 this document.

中的详细步骤进行操作

请查看文档 Sign in with Azure CLI 了解更多信息。

更新:使用powershell调用Azure rest API.

您可以使用 Invoke-RestMethod 调用 Azure rest API。您仍然需要为 API 调用提供身份验证。您可以参考下面的示例 this blog.

function Get-AccessToken {
    $context = Get-AzContext
    $profile = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile
    $profileClient = New-Object -TypeName Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient -ArgumentList ($profile)
    $token = $profileClient.AcquireAccessToken($context.Subscription.TenantId)
    return $token.AccessToken
}
$subscriptionid = "subscriptionid"
$rg_name = "off-rg"
$rm_endpoint = "https://management.azure.com"
$authHeader = @{
    'Content-Type'  = 'application/json'
    'Authorization' = 'Bearer ' + (Get-AccessToken)
}

$uri = "$rm_endpoint/subscriptions/$subscriptionid/resourceGroups/$rg_name/providers/Microsoft.Compute/virtualMachines?api-version=2019-03-01"

$respone = Invoke-RestMethod -Method Get -Headers $authHeader -Uri $uri

您还可以查看博客 Access Azure REST API using PowerShell 了解更多信息。