从 Azure Powershell 函数应用检索密钥保管库机密时出错

Error retrieving key vault secret from Azure Powershell Function app

我正在尝试使用以下步骤从 Timer Triggered Powershell Azure 函数应用访问密钥保管库机密。

  1. 已创建 TimerTrigger Powershell 函数应用程序。
  2. 在快速模式下使用 AD 应用程序注册函数应用程序。
  3. 在函数 App 中启用托管服务标识。
  4. 在同一资源组中创建了 KeyVault,并在 keyvault accesspolicies 下添加了函数应用程序。
  5. 在 keyvault 机密下创建了一个新机密。
  6. 使用下面的代码访问函数应用程序中的 keyvault。

    $NewTestSecret = Get-AzureKeyVaultSecret -VaultName FunctionAppTestKeyVault -Name TestSecret
    
    $NewTestSecretVaule = $NewTestSecret.SecretValueText
    
    Write-Output $NewTestSecretVaule
    

获取以下内容 errors.Not 确定我还缺少哪些额外的步骤。 非常感谢任何回复。

CategoryInfo : InvalidOperation: (:)

[Get-AzureKeyVaultSecret], PSInvalidOperationException

FullyQualifiedErrorId : InvalidOperation,Microsoft.Azure.Commands.KeyVault.GetAzureKeyVaultSecret 2018-04-14T17:45:00.709 [Error] Exception while executing function: Functions.TimerTriggerTestPowershell1. Microsoft.Azure.WebJobs.Script: PowerShell script error. Microsoft.Azure.Commands.ResourceManager.Common: Run Login-AzureRmAccount to login.

I am trying to access key vault secret from Timer Triggered Powershell Azure function app using the below steps.

如果要使用Get-AzureKeyVaultSecret命令,需要先登录-AzureRmAccount

默认情况下,Login-AzureRmAccount 进行 interactive 登录,这在 Azure Functions 中不起作用。相反,您需要使用服务主体登录,例如

Connect-AzureRmAccount -ServicePrincipal -ApplicationId  "http://my-app" -Credential $pscredential -TenantId $tenantid

您可以从 here. You also need to authorize the application to use the key or secret 获得更多信息。

另一种方式:

您也可以使用 MSI 函数来执行此操作。我们可以从这个 document. You also need the add the permisson to let azure function to access the keyvault. For more detail steps, you could refer to this guide.

得到访问码

演示代码:

$vaultName = "Your key vault name" 
$vaultSecretName = "your scecretname "

$tokenAuthURI = $Env:MSI_ENDPOINT + "?resource=https://vault.azure.net&api-version=2017-09-01"
$tokenResponse = Invoke-RestMethod -Method Get -Headers @{"Secret"="$env:MSI_SECRET"} -Uri $tokenAuthURI
$accessToken = $tokenResponse.access_token

$headers = @{ 'Authorization' = "Bearer $accessToken" }
$queryUrl = "https://$vaultName.vault.azure.net/secrets/" +$vaultSecretName + "?api-version=2016-10-01"

$keyResponse = Invoke-RestMethod -Method GET -Uri $queryUrl -Headers $headers

谢谢大家的回复。除了在 function app 中实现 MSI 之外,我还使用以下代码使用指纹证书从 Powershell function app 获取 keyvault 机密。

Add-AzureRmAccount -CertificateThumbprint "***********" -Tenant "*********" 
-ServicePrincipal -ApplicationId "**********"

$secret = Get-AzureKeyVaultSecret -VaultName "testkeyvault" -Name 
         "testSecret"

写入输出 $secret.SecretValueText

此外,WEBSITE_LOAD_CERTIFICATES 必须在应用程序设置下添加应用程序设置,以便将证书加载到函数应用程序中。