如何使用Powershell功能应用程序检索存储帐户密钥?

时间:2020-05-14 14:20:41

标签: azure powershell azure-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 [Error]错误:Get-AzStorageAccountKey:'this.Client.SubscriptionId'不能为null。 在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'不能为null。 Microsoft.Azure.Management.Storage.StorageAccountsOperations.ListKeysWithHttpMessagesAsync(String resourceGroupName,String accountName,Nullable 1 expand, Dictionary 2 customHeaders,CancellationToken cancelleToken) 位于Microsoft.Azure.Management.Storage.StorageAccountsOperationsExtensions.ListKeysAsync(IStorageAccountsOperations操作,字符串resourceGroupName,字符串accountName,可空1 expand, CancellationToken cancellationToken) at Microsoft.Azure.Management.Storage.StorageAccountsOperationsExtensions.ListKeys(IStorageAccountsOperations operations, String resourceGroupName, String accountName, Nullable 1展开) 在Microsoft.Azure.Commands.Management.Storage.GetAzureStorageAccountKeyCommand.ExecuteCmdlet()

1 个答案:

答案 0 :(得分:1)

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

例如

  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. 将该角色分配给服务主体。例如,在订阅级别上将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