I am doing a bit of cleaning up at work, merging some of my Automation Accounts, moving stuff around, renaming some Key Vaults (why is naming something so hard!!?) and wanted to get a list of all my Key Vaults and their Access Policies.
I had been maintaining a list in SharePoint Online manually, but I don’t trust myself. :) Wanted to generate something to get the current state. I came up with the following PowerShell script:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
$vaults = @{} $appIds = @{} # List all the Key Vault and process them Get-AzKeyVault | ForEach-Object{ $vaultName = $_.VaultName Write-Host "Processing $vaultName" # To get the Access Policies we need to get the Key Vault directly $accessPolicies = (Get-AzKeyVault -VaultName $_.VaultName -ErrorVariable warning).AccessPolicies # To my vaults hash table add the Vault name as a key $vaults.$vaultName = @{} # Process each Access Policy foreach ($accessPolicy in $accessPolicies) { # Strip out the app Id/ username from the Access Policy so it's just the name $displayName = $accessPolicy.DisplayName -replace '\s\([^\s]+\)$','' # Make a new temporary hash with the permissions. I am only interested in these three but there are a few more. $tempHash = [ordered]@{ "PermissionsToCertificates" = "" "PermissionsToKeys" = "" "PermissionsToSecrets" = "" } # Get the values, combine them into a single string for each permission type. Assign these to the hash table above. $tempHash.PermissionsToCertificates = $accessPolicy.PermissionsToCertificates -join "," $tempHash.PermissionsToKeys = $accessPolicy.PermissionsToKeys -join "," $tempHash.PermissionsToSecrets = $accessPolicy.PermissionsToSecrets -join "," # To the vaults hash table above, where I created a key with the vault name, I now create a new hash table with the key as the display name of the app/ user. # And I assign the temporary hash table as a value of that. # Thus $vaults.'vaultname1'.'appId' gives me the permissions. Neat huh! :) $vaults.$vaultName[$displayName] = $tempHash # Do the same for the hash tables of app Ids. I call this app Ids but they also include users. I am mainly interested in app Ids hence the name. # If the appIds hash table already contains a key with the display name of the app, I create a value in that similar to what I did above. # But if it does not contain a key, then I create that key and set its value as a hash table. Then I do the same as above. if ($appIds.ContainsKey($displayName)) { $appIds.$displayName[$vaultName] = $tempHash } else { $appIds.$displayName = @{} $appIds.$displayName[$vaultName] = $tempHash } } } |
Maybe it helps someone…