如何使用 powershell 函数应用程序检索存储帐户密钥?

How to retrieve storage account key using powershell function app?

我正在使用 powershell 函数应用程序检索存储帐户密钥,但我无法访问资源。请帮助我。

$resourceGroup = "DemoResourceGroup"

$AccountName = "Demo"

$Key = (Get-AzStorageAccountKey -ResourceGroupName $resourceGroup -Name $AccountName)

Write-Host "storage account key 1 = " $Key

我遇到以下错误:

2020-05-14T14:00:05Z [错误] 错误:Get-AzStorageAccountKey:'this.Client.SubscriptionId' 不能为空。 在 D:\home\site\wwwroot\TimerTrigger1\run.ps1:25 char:8 + $key = Get-AzStorageAccountKey -ResourceGroupName "DocumentParser_FBI ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~ + CategoryInfo : CloseError: (:) [Get-AzStorageAccountKey], ValidationException + FullyQualifiedErrorId : Microsoft.Azure.Commands.Management.Storage.GetAzureStorageAccountKeyCommand

脚本堆栈跟踪: 在 , D:\home\site\wwwroot\TimerTrigger1\run.ps1: 第 25 行

Microsoft.Rest.ValidationException: 'this.Client.SubscriptionId' 不能为空。 在 Microsoft.Azure.Management.Storage.StorageAccountsOperations.ListKeysWithHttpMessagesAsync(String resourceGroupName, String accountName, Nullable1 expand, Dictionary2 customHeaders, CancellationToken cancellationToken) 在 Microsoft.Azure.Management.Storage.StorageAccountsOperationsExtensions.ListKeysAsync(IStorageAccountsOperations 操作,String resourceGroupName,String accountName,Nullable1 expand, CancellationToken cancellationToken) at Microsoft.Azure.Management.Storage.StorageAccountsOperationsExtensions.ListKeys(IStorageAccountsOperations operations, String resourceGroupName, String accountName, Nullable1 展开) 在 Microsoft.Azure.Commands.Management.Storage.GetAzureStorageAccountKeyCommand.ExecuteCmdlet()

根据您提供的脚本,您使用了Az模块。所以如果你想选择你使用哪个Azure订阅,你需要使用命令Select-AzSubscription。此外,您还可以在Connect-AzAccoun中添加-Subscription "<subscription Id>",以确保您在登录时选择正确的订阅。

例如

  1. 创建服务主体
Import-Module Az.Resources # Imports the PSADPasswordCredential object
$credentials = New-Object Microsoft.Azure.Commands.ActiveDirectory.PSADPasswordCredential -Property @{ StartDate=Get-Date; EndDate=Get-Date -Year 2024; Password=<Choose a strong password>}
$sp = New-AzAdServicePrincipal -DisplayName ServicePrincipalName -PasswordCredential $credentials
  1. 将角色分配给服务主体。例如,将 Contributor 角色分配给订阅级别的 sp
New-AzRoleAssignment -ApplicationId <service principal application ID> -RoleDefinitionName "Contributor" `
-Scope "/subscriptions/<subscription id>"
  1. 脚本
$appId = "your sp app id"
$password = "your sp password"
$secpasswd = ConvertTo-SecureString $password -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ($appId, $secpasswd)

Connect-AzAccount -ServicePrincipal -Credential $mycreds -Tenant <you sp tenant id>
Get-AzSubscription -SubscriptionName "CSP Azure" | Select-AzSubscription

$resourceGroup = "nora4test"

$AccountName = "qsstorageacc"

$Key = (Get-AzStorageAccountKey -ResourceGroupName $resourceGroup -Name $AccountName)[0].Value

Write-Host "storage account key 1 = " $Key