Skip to content

Instantly share code, notes, and snippets.

@joanjane
Created September 14, 2018 10:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joanjane/160544ef4c3774c1a25cce81aefc5189 to your computer and use it in GitHub Desktop.
Save joanjane/160544ef4c3774c1a25cce81aefc5189 to your computer and use it in GitHub Desktop.
Assign/create a group of Azure MSI apps to key vault as an AAD group
# Run Connect-AzureAD and Connect-AzureRmAccount before executing this script
# https://docs.microsoft.com/en-us/azure/key-vault/key-vault-group-permissions-for-apps
# Ex.: ./assign-app-group-keyvault -appName "your-app-service-name" -vaultName "your-vault-name" -subscriptionName "your-subscription" -groupName "your-aad-group-name" -newGroup
param([string]$appName, [string]$vaultName, [string]$subscriptionName, [string]$groupName, [switch]$newGroup, [switch]$confirm)
function Confirm($message, $confirm) {
# Confirm prompt
if ($confirm -eq $false) {
$confirmation = Read-Host "$message [y/n]"
while ($confirmation -ne "y") {
if ($confirmation -eq 'n') { exit }
$confirmation = Read-Host $message
}
}
}
$aadGroup = $null
if ($newGroup) {
"Creating $groupName AAD group"
$aadGroup = New-AzureADGroup -DisplayName $groupName -MailEnabled 0 -MailNickName none -SecurityEnabled 1
"Group $($aadGroup.ObjectId) created"
} else {
$foundGroups = Get-AzureADGroup -SearchString $groupName
if ($foundGroups.Length -eq 0) {
throw "Group $groupName does not exist"
}
$aadGroup = $foundGroups[0]
}
Confirm -message "Do you want to proceed using AAD group $($aadGroup.ObjectId)" -confirm:$confirm
$spn = Get-AzureADServicePrincipal -SearchString $appName
if ($spn.Length -eq 0) {
throw "App $appName does not exist on this tenant"
}
$spnAlreadyAdded = (get-azureadgroupmember -ObjectId $aadGroup.ObjectId | Where-Object -Property ObjectId -eq $spn[0].ObjectId).Length -gt 0
if (!$spnAlreadyAdded) {
Confirm -message "Do you want to assign $($spn[0].DisplayName) on selected AAD group?" -confirm:$confirm
"Adding $($spn[0].ObjectId) on AAD group..."
Add-AzureADGroupMember -ObjectId $aadGroup.ObjectId -RefObjectId $spn[0].ObjectId
}
$subscription = Select-AzureRmSubscription -SubscriptionName $subscriptionName
"Assigning access policy of $($aadGroup.ObjectId) on $vaultName vault..."
Set-AzureRmKeyVaultAccessPolicy -VaultName $vaultName -ObjectId $aadGroup.ObjectId -PermissionsToKeys Get, List -PermissionsToSecrets Get, List -PermissionsToCertificates Get, List
"Finished!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment