从Azure Powershell Function应用检索关键文件库机密时出错

Error retrieving key vault secret from Azure Powershell Function app

我正在尝试使用以下步骤从Timer Triggered Powershell Azure功能应用程序访问密钥库机密。

  • 创建了TimerTrigger Powershell Function应用程序。
  • 在快速模式下向AD应用程序注册了功能应用程序。
  • 在功能App中启用了托管服务身份。
  • 在同一资源组中创建了KeyVault,并在keyvault访问策略下添加了功能应用程序。
  • 在密钥库机密下创建了一个新机密。
  • 使用以下代码访问功能应用程序中的密钥库。

    1
    2
    3
    4
    5
    $NewTestSecret = Get-AzureKeyVaultSecret -VaultName FunctionAppTestKeyVault -Name TestSecret

    $NewTestSecretVaule = $NewTestSecret.SecretValueText

    Write-Output $NewTestSecretVaule
  • 出现以下错误。不确定我还缺少哪些其他步骤。
    任何回复都非常感谢。

    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.


    谢谢大家的答复。除了在功能应用程序中实现MSI之外,我还使用下面的代码使用指纹证书从Powershell功能应用程序中获取密钥库的秘密。

    1
    2
    3
    4
    5
    Add-AzureRmAccount -CertificateThumbprint"***********" -Tenant"*********"
    -ServicePrincipal -ApplicationId"**********"

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

    写输出$ secret.SecretValueText

    还必须在应用程序设置下添加WEBSITE_LOAD_CERTIFICATES应用程序设置,以便将证书加载到功能应用程序中。


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

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

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

    )登录

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

    您可以从此处获取更多信息。您还需要授权应用程序使用密钥或机密。

    另一种方式:

    您也可以使用MSI功能来执行此操作。我们可以从该文档中获取访问代码。您还需要添加权限以让azure函数访问密钥库。有关更多详细步骤,请参阅本指南。

    演示代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    $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

    enter