The following forum(s) are migrating to a new home on Microsoft Q&A (Preview): Azure Key Vault!

Ask new questions on Microsoft Q&A (Preview).
Interact with existing posts until December 13, 2019, after which content will be closed to all new and existing posts.

Learn More

 none
Add-AzKeyVaultManagedStorageAccount : Operation returned an invalid status code 'Forbidden' RRS feed

  • Question


  • Hi, Please can I get help on this issue, trying to create a managed storage account

    PS C:\Users\flamidi> Get-AzADServicePrincipal|where-Object DisplayName -eq "lahmapp"|select-object ApplicationId

    ApplicationId                       
    -------------                       
    8a6cd318-24eb-4c93-b305-6825e6f56dcb

    PS C:\Users\flamidi> New-AzRoleAssignment -ApplicationId "8a6cd318-24eb-4c93-b305-6825e6f56dcb" -RoleDefinitionName 'Storage Account Key Operator Service Role' -Scope $storageAccount.Id

    RoleAssignmentId   : /subscriptions/xxxxxxx-xxxx-xxxx-xxxx-xxxxxx/resourceGroups/cmk-key-vault-5915/providers/Microsoft.Storage/storageAccounts/cmksa5915/providers/Microsoft.Authorization/roleAssignments/609707f9-011a-48ef-9906-d26bca2d361b
    Scope              : /subscriptions/xxxxxxx-xxxx-xxxx-xxxx-xxxxxx/resourceGroups/cmk-key-vault-5915/providers/Microsoft.Storage/storageAccounts/
                         cmksa5915
    DisplayName        : lahmapp
    SignInName         : 
    RoleDefinitionName : Storage Account Key Operator Service Role
    RoleDefinitionId   : 81a9662b-bebf-436f-a333-f67b29880f12
    ObjectId           : 6351dbd0-94e1-4a5c-a8df-03644e937a85
    ObjectType         : ServicePrincipal
    CanDelegate        : False

    PS C:\Users\flamidi> $managedStorageAccount = @{
        VaultName = $keyVault.VaultName
        AccountName = $storageAccount.StorageAccountName
        AccountResourceId = $storageAccount.Id
        ActiveKeyName = "key1"
        RegenerationPeriod = [System.Timespan]::FromDays(90)
    }

    PS C:\Users\flamidi> Add-AzKeyVaultManagedStorageAccount @managedStorageAccount
    Add-AzKeyVaultManagedStorageAccount : Operation returned an invalid status code 'Forbidden'
    At line:1 char:1
    + Add-AzKeyVaultManagedStorageAccount @managedStorageAccount
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : CloseError: (:) [Add-AzKeyVaultManagedStorageAccount], KeyVaultErrorException
        + FullyQualifiedErrorId : http://Microsoft.Azure.Commands.KeyVault.AddAzureKeyVaultManagedStorageAccount

    PS C:\Users\flamidi> $keyVault.VaultName
    cmk-key-vault-5915

    PS C:\Users\flamidi> $storageAccount.StorageAccountName
    cmksa5915

    PS C:\Users\flamidi> $storageAccount.Id
    /subscriptions/xxxxxxx-xxxx-xxxx-xxxx-xxxxxx/resourceGroups/cmk-key-vault-5915/providers/Microsoft.Storage/storageAccounts/cmksa5915

    PS C:\Users\flamidi>
    Thursday, November 7, 2019 5:56 AM

Answers

  • Hello flahm,

    You can use the following command to create a new KeyVault 

    New-AzKeyVault -Name "StorageTestVault"` 
       -ResourceGroupName $resourceGroupName` 
       -Location "southindia" 

    When you run this command, it pick up the user/app's idenity with which you are logged into that PS session (i.e connect-azAccount) and adds that user/app to the access policies of the KeyVault by default and provides all the available permissions including "PermissionToStorage". You can see the output of the command below:

    PS C:\windows\system32> New-AzKeyVault -Name "StorageTestVault" -ResourceGroupName $resourceGroupName -Location "southindia" 
    
    
    Vault Name                       : StorageTestVault
    Resource Group Name              : StorageKeyVaultRG
    Location                         : southindia
    Resource ID                      : /subscriptions/xxx-xxx-xxx-xxx/resourceGroups/StorageKeyVaultRG/providers/Microsoft.KeyVault/vaults/StorageTestVault
    Vault URI                        : https://storagetestvault.vault.azure.net/
    Tenant ID                        : xxx-xxx-xxxx-xxxx
    SKU                              : Standard
    Enabled For Deployment?          : False
    Enabled For Template Deployment? : False
    Enabled For Disk Encryption?     : False
    Soft Delete Enabled?             : 
    Access Policies                  : 
                                       Tenant ID                                  : xxxx-xxxx-xxxx-xxxx
                                       Object ID                                  : f0666658-c3e8-4d34-995e-2c5242df41d7
                                       Application ID                             : 
                                       Display Name                               : xxxx xxxx (xxxx@xxxx.onmicrosoft.com)
                                       Permissions to Keys                        : get, create, delete, list, update, import, backup, restore, recover
                                       Permissions to Secrets                     : get, list, set, delete, backup, restore, recover
                                       Permissions to Certificates                : get, delete, list, create, import, update, deleteissuers, getissuers, listissuers, managecontacts, 
                                       manageissuers, setissuers, recover, backup, restore
                                       Permissions to (Key Vault Managed) Storage : delete, deletesas, get, getsas, list, listsas, regeneratekey, set, setsas, update, recover, backup, restore
                                       
                                       
    Network Rule Set                 : 
                                       Default Action                             : Allow
                                       Bypass                                     : AzureServices
                                       IP Rules                                   : 
                                       Virtual Network Rules                      : 
                                       
    Tags                             : 
    
    

    In case you create a KeyVault from the Azure Portal, there also the user who is creating the KeyVault by default gets added under the Access Policies section of the KeyVault along with the permissions, but only the PermissionToStorage is not grant there. So its good to use the PS Cmdlet.

    In case you would like to add some other application or user under the Access Policies of the Azure KeyVault using the Powershell, then you can use the following cmdlet:

    Set-AzKeyVaultAccessPolicy -VaultName $keyVaultName` 
       -UserPrincipalName $userId` 
       -PermissionsToStorage get, list, delete, set, update, regeneratekey, getsas, listsas, deletesas, setsas, recover, backup, restore, purge

    Based on the current error you shared:

    Set-AzKeyVaultAccessPolicy : Cannot find the Active Directory object '' in tenant 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx'. Please make sure that the 
    user or application service principal you are authorizing is registered in the current subscription's Azure Active directory. The TenantID displayed 
    by the cmdlet 'Get-AzContext' is the current subscription's Azure Active directory.
    At line:1 char:1
    + Set-AzKeyVaultAccessPolicy -VaultName $keyVault.VaultName -UserPrinci ...
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : CloseError: (:) [Set-AzKeyVaultAccessPolicy], ArgumentException
        + FullyQualifiedErrorId : Microsoft.Azure.Commands.KeyVault.SetAzureKeyVaultAccessPolicy
    

    It looks like the userID you received from under your variable "$userId" could not be found in the tenant. Not really sure why.

    I am sharing my entire script with you below for you to have a complete view:

    Connect-AzAccount
    Set-AzContext -SubscriptionId "<subscription-id>"
    
    $resourceGroupName = "<RG-name>"
    $storageAccountName = "<Storage-Name>"
    $keyVaultName = "<Keyvault-Name>"
    $keyVaultSpAppId = "cfa8b339-82a2-471a-a3c9-0fc0be7a4093"
    $storageAccountKey = "key1"
    
    # Get your User Id
    $userId = (Get-AzContext).Account.Id
    
    # Get a reference to your Azure storage account
    $storageAccount = Get-AzStorageAccount -ResourceGroupName $resourceGroupName -StorageAccountName $storageAccountName
    
    # Assign RBAC role "Storage Account Key Operator Service Role" to Key Vault, limiting the access scope to your storage account. For a classic storage account, use "Classic Storage Account Key Operator Service Role." 
    New-AzRoleAssignment -ApplicationId $keyVaultSpAppId -RoleDefinitionName 'Storage Account Key Operator Service Role' -Scope $storageAccount.Id
    
    # Give your user principal access to all storage account permissions, on your Key Vault instance
    Set-AzKeyVaultAccessPolicy -VaultName $keyVaultName -UserPrincipalName $userId -PermissionsToStorage get, list, delete, set, update, regeneratekey, getsas, listsas, deletesas, setsas, recover, backup, restore, purge
    
    $regenerationPeriod = [System.Timespan]::FromDays(1)
    # Add your storage account to your Key Vault's managed storage accounts
    Add-AzKeyVaultManagedStorageAccount -VaultName $keyVaultName -AccountName $storageAccountName -AccountResourceId $storageAccount.Id -ActiveKeyName $storageAccountKey -RegenerationPeriod $regenerationPeriod

    Do let us know if this helps. if further queries, please feel free to let us know so that we can help you further in fixing this.

    ---------------------------------------------------------------------------------------------------------------------------------------

    Please take a moment to "Mark as Answer" and/or "Vote as Helpful" wherever applicable. Thanks!

    • Marked as answer by flahm Tuesday, November 12, 2019 5:30 PM
    Tuesday, November 12, 2019 8:14 AM
    Moderator

All replies

  • flahm, thank you for sharing the query. We are looking into this and will get back to you soon on this thread.
    Thursday, November 7, 2019 8:53 AM
    Moderator
  • flahm, In this case if your roleAssignement for the role "Storage Account Key Operator Service Role" on the storage account for the Key Vault has to be "cfa8b339-82a2-471a-a3c9-0fc0be7a4093" and not "8a6cd318-24eb-4c93-b305-6825e6f56dcb".

    Can you try adding the following app id "cfa8b339-82a2-471a-a3c9-0fc0be7a4093", in the following command and then check if it works or not:

    $keyVaultSpAppId = "cfa8b339-82a2-471a-a3c9-0fc0be7a4093"
    New-AzRoleAssignment -ApplicationId $keyVaultSpAppId -RoleDefinitionName 'Storage Account Key Operator Service Role' -Scope $storageAccount.Id

    Also, make sure that user account under who is running the script is added Access Policies of the Azure Key Vault with Permissions set for Secret as Get, Set, List.

    Hope this helps.

    ---------------------------------------------------------------------------------------------------------------------------------------

    Please take a moment to "Mark as Answer" and/or "Vote as Helpful" wherever applicable. Thanks!

    Thursday, November 7, 2019 9:25 AM
    Moderator
  • PS C:\Users> #Prefix for resources
    $prefix = "cmk"
    
    #Basic variables
    $location = "westus"
    $id = Get-Random -Minimum 1000 -Maximum 9999
    
    
    PS C:\Users> $id
    5121
    
    PS C:\Users> Get-AzSubscription -SubscriptionName "Azure subscription 1" | Select-AzSubscription
    
    Name                                     Account                                 
     SubscriptionName                         Environment                              TenantId       
                             
    ----                                     -------                                 
     ----------------                         -----------                              --------       
                             
    Azure subscription 1 (62096452-c1fe-4... xxxxxx@outlook.com                       Azure subscription 1                     AzureCloud   
                                xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx    
    
    
    
    PS C:\Users> $keyVaultGroup = New-AzResourceGroup -Name "$prefix-key-vault-$id" -Location $location
    
    PS C:\Users> $keyVaultParameters = @{
        Name = "$prefix-key-vault-$id"
        ResourceGroupName = $keyVaultGroup.ResourceGroupName
        Location = $location
        Sku = "Premium"
    }
    
    
    PS C:\Users> $keyVault = New-AzKeyVault @keyVaultParameters
    WARNING: The provided information does not map to an AD object id.
    WARNING: Access policy is not set. No user or application have access permission to use this vault. This can happen if the vault was created by a service principal. Please use Set-AzKeyVaultAccessPolicy to
     set access policies.
    
    PS C:\Users> $accessPolicy = @{
        VaultName = $keyVault.VaultName
        ServicePrincipalName  = "cfa8b339-82a2-471a-a3c9-0fc0be7a4093"
        PermissionsToStorage = ("get","list","listsas","delete","set","update","regeneratekey","recover","backup","restore","purge")
    }
    
    PS C:\Users> Set-AzKeyVaultAccessPolicy @accessPolicy
    
    PS C:\Users> $accessPolicy = @{
        VaultName = $keyVault.VaultName
        UserPrincipalName   = "xxxxxx_outlook.com#EXT#@xxxxxxoutlook.onmicrosoft.com"
        PermissionsToSecrets = ("get","list","delete","set")
    }
    
    
    PS C:\Users> Set-AzKeyVaultAccessPolicy @accessPolicy
    
    PS C:\Users> $keyVault | Format-List
    
    
    Vault Name                       : cmk-key-vault-5121
    Resource Group Name              : cmk-key-vault-5121
    Location                         : westus
    Resource ID                      : /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx/resourceGWhiteroups/cmk-key-vault-5121/providers/Microsoft.KeyVault/vaults/cmk-key-vault-5121
    Vault URI                        : https://cmk-key-vault-5121.vault.azure.net/
    Tenant ID                        : xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx
    SKU                              : Premium
    Enabled For Deployment?          : False
    Enabled For Template Deployment? : False
    Enabled For Disk Encryption?     : False
    Soft Delete Enabled?             : 
    Access Policies                  : 
    Network Rule Set                 : 
                                       Default Action                             : Allow
                                       Bypass                                   
      : AzureServices
                                       IP Rules                                   : 
                                       Virtual Network Rules                      : 
                                       
    Tags                             : 
    
    
    
    
    PS C:\Users> $saAccountParameters = @{
        Name = "$($prefix)sa$id"
        ResourceGroupName = $keyVaultGroup.ResourceGroupName
        Location = $location
        SkuName = "Standard_LRS"
    }
    
    PS C:\Users> $storageAccount = New-AzStorageAccount @saAccountParameters
    
    PS C:\Users> 
    $key1=(Get-AzStorageAccountKey -ResourceGroupName $storageAccount.ResourceGroupName -Name $storageAccount.StorageAccountName).value[0]
    $key2=(Get-AzStorageAccountKey -ResourceGroupName $storageAccount.ResourceGroupName -Name $storageAccount.StorageAccountName).value[1]
    
    
    
    PS C:\Users> $keyVaultSpAppId = "cfa8b339-82a2-471a-a3c9-0fc0be7a4093"
    
    PS C:\Users> New-AzRoleAssignment -ApplicationId $keyVaultSpAppId -RoleDefinitionName 'Storage Account Key Operator Service Role' -Scope $storageAccount.Id
    
    
    RoleAssignmentId   : /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx/resourceGroups/cmk-key-vault-5121/providers/Microsoft.Storage/storageAccounts/cmksa5121/providers/Microsoft.Authorization/roleAssig
                         nments/647a54f8-a475-4662-8277-6450011e1a72
    Scope              : /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx/resourceGroups/cmk-key-vault-5121/providers/Microsoft.Storage/storageAccounts/cmksa5121
    DisplayName        : Azure Key Vault
    SignInName         : 
    RoleDefinitionName : Storage Account Key Operator Service Role
    RoleDefinitionId   : 81a9662b-bebf-436f-a333-f67b29880f12
    ObjectId           : e59703a6-70cd-4456-be09-ff6c3685bbdf
    ObjectType         : ServicePrincipal
    CanDelegate        : False
    
    
    
    
    PS C:\Users> $managedStorageAccount = @{
        VaultName = $keyVault.VaultName
        AccountName = $storageAccount.StorageAccountName
        AccountResourceId = $storageAccount.Id
        ActiveKeyName = "key1"
        RegenerationPeriod = [System.Timespan]::FromDays(90)
    }
    
    PS C:\Users> Add-AzKeyVaultManagedStorageAccount @managedStorageAccount
    Add-AzKeyVaultManagedStorageAccount : Operation returned an invalid status code 'Forbidden'
    At line:1 char:1
    + Add-AzKeyVaultManagedStorageAccount @managedStorageAccount
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : CloseError: (:) [Add-AzKeyVaultManagedStorageAccount], KeyVaultErrorException
        + FullyQualifiedErrorId : Microsoft.Azure.Commands.KeyVault.AddAzureKeyVaultManagedStorageAccount
     

    Still getting the same error
    • Edited by flahm Saturday, November 9, 2019 8:19 AM
    Saturday, November 9, 2019 8:13 AM
  • Hi,

    Do you have an update?

    Thanks,

    Fiyin


    Lahm01

    Monday, November 11, 2019 11:10 PM
  • Hello flahm, 

    I apologize for the delay in my response, as i was tied up with few other commitments.

    I did check your cmdlets and the outputs that you shared. Now based on the final error, the issue is still regarding Permissions. Now while i checked your cmdlets thoroughly, i see that your KeyVault doesnt have any access policies defined for it.

    Your output:

    PS C:\Users> $keyVault | Format-List
    
    
    Vault Name                       : cmk-key-vault-5121
    Resource Group Name              : cmk-key-vault-5121
    Location                         : westus
    Resource ID                      : /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx/resourceGWhiteroups/cmk-key-vault-5121/providers/Microsoft.KeyVault/vaults/cmk-key-vault-5121
    Vault URI                        : https://cmk-key-vault-5121.vault.azure.net/
    Tenant ID                        : xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx
    SKU                              : Premium
    Enabled For Deployment?          : False
    Enabled For Template Deployment? : False
    Enabled For Disk Encryption?     : False
    Soft Delete Enabled?             : 
    Access Policies                  : 
    Network Rule Set                 : 
                                       Default Action                             : Allow
                                       Bypass                                   
      : AzureServices
                                       IP Rules                                   : 
                                       Virtual Network Rules                      : 
                                       
    Tags                             : 
    


    Output from my repro:

    PS C:\windows\system32> Get-AzKeyVault -VaultName StorageKeyVault1112 | fl
    
    
    Vault Name                       : StorageKeyVault1112
    Resource Group Name              : StorageKeyVaultRG
    Location                         : northcentralus
    Resource ID                      : /subscriptions/04c48986-6495-4bf4-b098-92e5f1233cf0/resourceGroups/StorageKeyVaultRG/prov
                                       iders/Microsoft.KeyVault/vaults/StorageKeyVault1112
    Vault URI                        : https://storagekeyvault1112.vault.azure.net/
    Tenant ID                        : c2d4955e-81d6-462b-8388-68a5ce8dc243
    SKU                              : Standard
    Enabled For Deployment?          : False
    Enabled For Template Deployment? : False
    Enabled For Disk Encryption?     : False
    Soft Delete Enabled?             : 
    Access Policies                  : 
                                       Tenant ID                                  : c2d4955e-81d6-462b-8388-68a5ce8dc243
                                       Object ID                                  : f0666658-c3e8-4d34-995e-2c5242df41d7
                                       Application ID                             : 
                                       Display Name                               : Sourav Mishra 
                                       (sourav@soumimsft.onmicrosoft.com)
                                       Permissions to Keys                        : Get, List, Update, Create, Import, Delete, 
                                       Recover, Backup, Restore
                                       Permissions to Secrets                     : Get, List, Set, Delete, Recover, Backup, 
                                       Restore
                                       Permissions to Certificates                : Get, List, Update, Create, Import, Delete, 
                                       Recover, Backup, Restore, ManageContacts, ManageIssuers, GetIssuers, ListIssuers, 
                                       SetIssuers, DeleteIssuers
                                       Permissions to (Key Vault Managed) Storage : get, list, delete, set, update, 
                                       regeneratekey, getsas, listsas, deletesas, setsas, recover, backup, restore, purge
                                       
                                       
    Network Rule Set                 : 
                                       Default Action                             : Allow
                                       Bypass                                     : AzureServices
                                       IP Rules                                   : 
                                       Virtual Network Rules                      : 
                                       
    Tags                             : 


    Now, if you compare both the outputs you will find that for my lab repro, I have access policies listed under the get-azKeyVault cmdlet.

    Also, another thing that I found in your cmdlets that you ran was that you did try to assign the Access policies to the key vault but somehow the assignment didnt work out and secondly, you tried assigning the KeyVault's App id the following permissions for managing the storage ""get","list","listsas","delete","set","update","regeneratekey","recover","backup","restore","purge"" as per the cmdlet here:

    PS C:\Users> $accessPolicy = @{
        VaultName = $keyVault.VaultName
        ServicePrincipalName  = "cfa8b339-82a2-471a-a3c9-0fc0be7a4093"
        PermissionsToStorage = ("get","list","listsas","delete","set","update","regeneratekey","recover","backup","restore","purge")
    }
    


    This is not correct. In the access policies, you need to add the AppID (in case the operation is happening under an application) or an UPN of the user (if the operation is happening under an user) but not the KeyVault's App ID.

    So the correct cmdlet to run would be:

    $userId = (Get-AzContext).Account.Id
    
    Set-AzKeyVaultAccessPolicy -VaultName $keyVaultName` 
       -UserPrincipalName $userId` 
       -PermissionsToStorage get, list, delete, set, update, regeneratekey, getsas, listsas, deletesas, setsas, recover, backup, restore, purge
    

    I also tried to bring up that same "Forbidden" in an effort to reproduce the issue. I created a fresh Azure KeyVault and another Storage Account. Now for this new KeyVault, I have not added the user to the access policies for PermissionToStorage as you can see below:



    Once you run the cmdlet: it would fail with the "Forbidden" error as below:

    Hope this helps in fixing the issue.

    ---------------------------------------------------------------------------------------------------------------------------------------

    Please take a moment to "Mark as Answer" and/or "Vote as Helpful" wherever applicable. Thanks!

    Tuesday, November 12, 2019 6:03 AM
    Moderator
  • Hi Sourav,

    Thanks for the update, I appreciate the time you took in setting up the repro. I did the below and still got the same error, I am logged in as the global admin, should I use the UPN of the Global admin, or the AppID of the registered AD app, also I'll appreciate it if you could try the steps in this link - https://blog.ipswitch.com/deploy-a-managed-storage-account-in-microsoft-azure or https://docs.microsoft.com/en-us/azure/key-vault/key-vault-overview-storage-keys-powershell to see if it works for you, I'll appreciate the repro so I can follow the steps


    PS C:\Users\> Set-AzKeyVaultAccessPolicy -VaultName 'cmk-key-vault-5387' -ObjectId '6351dbd0-94e1-4a5c-a8df-03644e937a85' -PermissionsToStorage get, list, delete, set, update, regeneratekey, getsas, listsas, deletesas, setsas, recover, backup, restore, purge

    PS C:\Users\>  Get-AzKeyVault -VaultName $keyVault.VaultName | fl


    Vault Name                       : cmk-key-vault-5387
    Resource Group Name              : cmk-key-vault-5387
    Location                         : westus
    Resource ID                      : /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx/resourceGroups/cmk-key-vault-5387/providers/Microsoft.KeyVault/vaults/cmk-key-vault-5387
    Vault URI                        : https://cmk-key-vault-5387.vault.azure.net/
    Tenant ID                        : xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx
    SKU                              : Premium
    Enabled For Deployment?          : False
    Enabled For Template Deployment? : False
    Enabled For Disk Encryption?     : False
    Soft Delete Enabled?             : 
    Access Policies                  : 
                                       Tenant ID                                  : xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx
                                       Object ID                                  : 6351dbd0-94e1-4a5c-a8df-03644e937a85
                                       Application ID                             : 
                                       Display Name                               : lahmapp (8a6cd318-24eb-4c93-b305-6825e6f56dcb)
                                       Permissions to Keys                        : 
                                       Permissions to Secrets                     : 
                                       Permissions to Certificates                : 
                                       Permissions to (Key Vault Managed) Storage : get, list, delete, set, update, regeneratekey, getsas, listsas, 
                                       deletesas, setsas, recover, backup, restore, purge
                                       
                                       
    Network Rule Set                 : 
                                       Default Action                             : Allow
                                       Bypass                                     : AzureServices
                                       IP Rules                                   : 
                                       Virtual Network Rules                      : 
                                       
    Tags                             : 




    PS C:\Users\> $saAccountParameters = @{
        Name = "$($prefix)sa$id"
        ResourceGroupName = $keyVaultGroup.ResourceGroupName
        Location = $location
        SkuName = "Standard_LRS"
    }


    PS C:\Users\> $storageAccount = New-AzStorageAccount @saAccountParameters

    PS C:\Users\> $key1=(Get-AzStorageAccountKey -ResourceGroupName $storageAccount.ResourceGroupName -Name $storageAccount.StorageAccountName).value[0]
    $key2=(Get-AzStorageAccountKey -ResourceGroupName $storageAccount.ResourceGroupName -Name $storageAccount.StorageAccountName).value[1]



    PS C:\Users\> $keyVaultSpAppId = "cfa8b339-82a2-471a-a3c9-0fc0be7a4093"

    PS C:\Users\> New-AzRoleAssignment -ApplicationId $keyVaultSpAppId -RoleDefinitionName 'Storage Account Key Operator Service Role' -Scope $storageAccount.Id


    RoleAssignmentId   : /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx/resourceGroups/cmk-key-vault-5387/providers/Microsoft.Storage/storageAccounts/
                         cmksa5387/providers/Microsoft.Authorization/roleAssignments/ceb53537-b1c2-430c-a3d8-c054d18c593a
    Scope              : /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx/resourceGroups/cmk-key-vault-5387/providers/Microsoft.Storage/storageAccounts/
                         cmksa5387
    DisplayName        : Azure Key Vault
    SignInName         : 
    RoleDefinitionName : Storage Account Key Operator Service Role
    RoleDefinitionId   : 81a9662b-bebf-436f-a333-f67b29880f12
    ObjectId           : e59703a6-70cd-4456-be09-ff6c3685bbdf
    ObjectType         : ServicePrincipal
    CanDelegate        : False




    PS C:\Users\> $managedStorageAccount = @{
        VaultName = $keyVault.VaultName
        AccountName = $storageAccount.StorageAccountName
        AccountResourceId = $storageAccount.Id
        ActiveKeyName = "key1"
        RegenerationPeriod = [System.Timespan]::FromDays(90)
    }

    PS C:\Users\> Add-AzKeyVaultManagedStorageAccount @managedStorageAccount
    Add-AzKeyVaultManagedStorageAccount : Operation returned an invalid status code 'Forbidden'
    At line:1 char:1
    + Add-AzKeyVaultManagedStorageAccount @managedStorageAccount
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : CloseError: (:) [Add-AzKeyVaultManagedStorageAccount], KeyVaultErrorException
        + FullyQualifiedErrorId : Microsoft.Azure.Commands.KeyVault.AddAzureKeyVaultManagedStorageAccount
     

    PS C:\Users\> 

    Thanks,

    Fiyin


    Lahm01

    Tuesday, November 12, 2019 7:26 AM
  • Hello flahm,

    You can use the following command to create a new KeyVault 

    New-AzKeyVault -Name "StorageTestVault"` 
       -ResourceGroupName $resourceGroupName` 
       -Location "southindia" 

    When you run this command, it pick up the user/app's idenity with which you are logged into that PS session (i.e connect-azAccount) and adds that user/app to the access policies of the KeyVault by default and provides all the available permissions including "PermissionToStorage". You can see the output of the command below:

    PS C:\windows\system32> New-AzKeyVault -Name "StorageTestVault" -ResourceGroupName $resourceGroupName -Location "southindia" 
    
    
    Vault Name                       : StorageTestVault
    Resource Group Name              : StorageKeyVaultRG
    Location                         : southindia
    Resource ID                      : /subscriptions/xxx-xxx-xxx-xxx/resourceGroups/StorageKeyVaultRG/providers/Microsoft.KeyVault/vaults/StorageTestVault
    Vault URI                        : https://storagetestvault.vault.azure.net/
    Tenant ID                        : xxx-xxx-xxxx-xxxx
    SKU                              : Standard
    Enabled For Deployment?          : False
    Enabled For Template Deployment? : False
    Enabled For Disk Encryption?     : False
    Soft Delete Enabled?             : 
    Access Policies                  : 
                                       Tenant ID                                  : xxxx-xxxx-xxxx-xxxx
                                       Object ID                                  : f0666658-c3e8-4d34-995e-2c5242df41d7
                                       Application ID                             : 
                                       Display Name                               : xxxx xxxx (xxxx@xxxx.onmicrosoft.com)
                                       Permissions to Keys                        : get, create, delete, list, update, import, backup, restore, recover
                                       Permissions to Secrets                     : get, list, set, delete, backup, restore, recover
                                       Permissions to Certificates                : get, delete, list, create, import, update, deleteissuers, getissuers, listissuers, managecontacts, 
                                       manageissuers, setissuers, recover, backup, restore
                                       Permissions to (Key Vault Managed) Storage : delete, deletesas, get, getsas, list, listsas, regeneratekey, set, setsas, update, recover, backup, restore
                                       
                                       
    Network Rule Set                 : 
                                       Default Action                             : Allow
                                       Bypass                                     : AzureServices
                                       IP Rules                                   : 
                                       Virtual Network Rules                      : 
                                       
    Tags                             : 
    
    

    In case you create a KeyVault from the Azure Portal, there also the user who is creating the KeyVault by default gets added under the Access Policies section of the KeyVault along with the permissions, but only the PermissionToStorage is not grant there. So its good to use the PS Cmdlet.

    In case you would like to add some other application or user under the Access Policies of the Azure KeyVault using the Powershell, then you can use the following cmdlet:

    Set-AzKeyVaultAccessPolicy -VaultName $keyVaultName` 
       -UserPrincipalName $userId` 
       -PermissionsToStorage get, list, delete, set, update, regeneratekey, getsas, listsas, deletesas, setsas, recover, backup, restore, purge

    Based on the current error you shared:

    Set-AzKeyVaultAccessPolicy : Cannot find the Active Directory object '' in tenant 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx'. Please make sure that the 
    user or application service principal you are authorizing is registered in the current subscription's Azure Active directory. The TenantID displayed 
    by the cmdlet 'Get-AzContext' is the current subscription's Azure Active directory.
    At line:1 char:1
    + Set-AzKeyVaultAccessPolicy -VaultName $keyVault.VaultName -UserPrinci ...
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : CloseError: (:) [Set-AzKeyVaultAccessPolicy], ArgumentException
        + FullyQualifiedErrorId : Microsoft.Azure.Commands.KeyVault.SetAzureKeyVaultAccessPolicy
    

    It looks like the userID you received from under your variable "$userId" could not be found in the tenant. Not really sure why.

    I am sharing my entire script with you below for you to have a complete view:

    Connect-AzAccount
    Set-AzContext -SubscriptionId "<subscription-id>"
    
    $resourceGroupName = "<RG-name>"
    $storageAccountName = "<Storage-Name>"
    $keyVaultName = "<Keyvault-Name>"
    $keyVaultSpAppId = "cfa8b339-82a2-471a-a3c9-0fc0be7a4093"
    $storageAccountKey = "key1"
    
    # Get your User Id
    $userId = (Get-AzContext).Account.Id
    
    # Get a reference to your Azure storage account
    $storageAccount = Get-AzStorageAccount -ResourceGroupName $resourceGroupName -StorageAccountName $storageAccountName
    
    # Assign RBAC role "Storage Account Key Operator Service Role" to Key Vault, limiting the access scope to your storage account. For a classic storage account, use "Classic Storage Account Key Operator Service Role." 
    New-AzRoleAssignment -ApplicationId $keyVaultSpAppId -RoleDefinitionName 'Storage Account Key Operator Service Role' -Scope $storageAccount.Id
    
    # Give your user principal access to all storage account permissions, on your Key Vault instance
    Set-AzKeyVaultAccessPolicy -VaultName $keyVaultName -UserPrincipalName $userId -PermissionsToStorage get, list, delete, set, update, regeneratekey, getsas, listsas, deletesas, setsas, recover, backup, restore, purge
    
    $regenerationPeriod = [System.Timespan]::FromDays(1)
    # Add your storage account to your Key Vault's managed storage accounts
    Add-AzKeyVaultManagedStorageAccount -VaultName $keyVaultName -AccountName $storageAccountName -AccountResourceId $storageAccount.Id -ActiveKeyName $storageAccountKey -RegenerationPeriod $regenerationPeriod

    Do let us know if this helps. if further queries, please feel free to let us know so that we can help you further in fixing this.

    ---------------------------------------------------------------------------------------------------------------------------------------

    Please take a moment to "Mark as Answer" and/or "Vote as Helpful" wherever applicable. Thanks!

    • Marked as answer by flahm Tuesday, November 12, 2019 5:30 PM
    Tuesday, November 12, 2019 8:14 AM
    Moderator