############################################################################################ # This runbook script grants key vaults access policies to Applications by their ObjectID. # # Please note that every subscription must be defined with an Automation account and have # # this runbook defined. # # In addition the objectId used must be taken from the properties pane of the # # Managed application in local directory (need to press the link with the application name)# # that need to be granted the access policies and not the objectID specified in the # # default proiperties pane. # # Requirments # # ----------- # # 1. The Automation account needs to have owner role for the subscription # # 2. Update to latest modules version: Automation Account -> Shared Resources -> Modules # # -> Update Azure Modules # ############################################################################################ try { Write-output(" Logging in to Azure..."); Connect-AzAccount -Identity Write-output(" Logged in to Azure..."); } catch{ if (!$servicePrincipalConnection) { $ErrorMessage = "Connection $connectionName not found." throw $ErrorMessage } else{ Write-Error -Message $_.Exception throw $_.Exception } } Write-output(" Login to Azure Successful.") $subscriptionId = "427eee31-104c-4fab-b342-44a939630286" #specify Key vaults to exclude $excludedKeyVaults = "" #specify Applications object id to grant access policies to $objectIds = "42701016-cce1-4fd2-9d6f-b895d1fa96d8" try { #List all the subscription key vaults... Write-output(" Listing key vaults...") # $KeyVaults = Get-AzKeyVault -SubscriptionId $subscriptionId $KeyVaults = Get-AzKeyVault Write-output(" Found " + $KeyVaults.Count + " Key vaults") } catch { Write-output(" Failed to list KeyVaults:") Write-Error -Message $_.Exception throw $_.Exception } # Iterate all key vaults found foreach($KeyVault in $KeyVaults) { try { # Skip specified excluded key vaults if($excludedKeyVaults -contains $KeyVault.VaultName) { Write-output(" Skipping " + $KeyVault.VaultName + ". Set in excluded Key vaults.") } else { Write-output(" Start handling Key vault " + $KeyVault.VaultName + "...") # Iterate all object ids to grant access policies to foreach($objectId in $objectIds) { Write-output(" Granting access policies to objectId " + $objectId + " ...") $output = $null; $output = Set-AzKeyVaultAccessPolicy -BypassObjectIdValidation -VaultName $KeyVault.VaultName -ObjectId $objectId -PermissionsToKeys 'list' -PermissionsToSecrets 'list' -PermissionsToCertificates get, list 2>&1 if(!$output) { Write-output(" " + $KeyVault.VaultName + " Access policies granted successfully for objectId " + $objectId) } else { Write-output(" Failed to grant access policies to objectId " + $objectId) } } Write-output(" Finshied handling key vault " + $KeyVault.VaultName) } } catch { Write-output(" Failed to set permissions for KeyVault " + $KeyVault.VaultName) Write-Error -Message $_.Exception throw $_.Exception } }