如何在同一资源组中的Azure Function应用中设置Key Vault机密?

时间:2020-06-01 18:02:20

标签: azure azure-functions azure-powershell azure-keyvault azure-function-app

我想设置一个Azure功能,该功能每4小时运行一次,从URL中检索一个JWK(这不是我在下面显示的那个),并将其作为秘密保存到Key Vault中。

当我在命令行上尝试Powershell代码时,它就可以工作:

PS C:\> $x5c = (Invoke-WebRequest https://login.microsoftonline.com/common/discovery/v2.0/keys |
>> ConvertFrom-Json |
>> Select-Object -expand keys |
>> Where-Object -Property kid -Eq SsZsBNhZcF3Q9S4trpQBTByNRRI) |
>> Select-Object -expand x5c
PS C:\> $secretvalue = ConvertTo-SecureString $x5c -AsPlainText -Force
PS C:\> $secret = Set-AzKeyVaultSecret -VaultName my-keyvault -Name 'MyLittleSecret' -SecretValue $secretvalue

我可以在Key Vault中看到秘密:

key vault screenshot

但是,当我尝试设置定时的Azure函数时,单击“运行”时什么也没有发生:

function app

我认为作为功能新手,我正在错误的位置查找日志...但是即使找到它们,这是执行任务的正确方法吗?

  1. Azure PowerShell是否可以在功能中使用?
  2. 首先需要Login-AzAccount吗?

3 个答案:

答案 0 :(得分:3)

Azure PowerShell是否可以在功能中使用?

是的,它将起作用。

是否需要先登录Login-AzAccount?

不,您不需要这样做。


有关更多详细信息,请按照以下步骤操作。

1。确保您使用以下设置创建了功能应用。

enter image description here

2。创建功能应用程序后,在门户中导航至应用程序的Identity,启用系统分配的MSI,如下所示。

enter image description here

3。在门户中导航至密钥库-> Access policies-> Add Access Policy->搜索您的函数名称(MSI与您的函数名称相同)并添加正确的秘密权限。

enter image description here

4。在该功能中,无需手动登录,它将自动以MSI登录,只需使用下面的命令,对我来说就可以正常工作。

param($Timer)

$x5c = (Invoke-WebRequest https://login.microsoftonline.com/common/discovery/v2.0/keys | ConvertFrom-Json |Select-Object -expand keys |Where-Object -Property kid -Eq SsZsBNhZcF3Q9S4trpQBTByNRRI) | Select-Object -expand x5c
$secretvalue = ConvertTo-SecureString $x5c -AsPlainText -Force
$secret = Set-AzKeyVaultSecret -VaultName joykeyvault -Name 'MyLittleSecret' -SecretValue $secretvalue
Write-Host $secret.Name

enter image description here

检查密钥库:

enter image description here

答案 1 :(得分:1)

另一种替代方法是在运行时从keyvault中获取它并将其存储在配置中,然后在代码中使用配置值。 请参阅:https://docs.microsoft.com/en-us/azure/app-service/app-service-key-vault-references

配置将如下所示 用户名KV: @ Microsoft.KeyVault(SecretUri = https://myvault.vault.azure.net/secrets/mysecret/ec96f02080254f109c51a1f14cdb1931) 密码KV: @ Microsoft.KeyVault(SecretUri = https://myvault.vault.azure.net/secrets/mysecret/ec96f02080254f109c51a1f14cdb1931)

答案 2 :(得分:0)

Does Azure PowerShell work in a Function?

是的,您可以使用Powershell创建Azure函数。 this应该可以为您

Does it require a Login-AzAccount first?

是的,如果您需要一些与Azure资源相关的逻辑,则需要它。

当涉及到实际问题时,我认为您需要压缩该功能并将其上传到azure功能应用,

压缩文件夹以上传Azure功能

Compress-Archive -Path * -DestinationPath Function1.zip