Export/Private/Set-KeyVaultPermissionsForScaleSet.ps1

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
function Global:Set-KeyVaultPermissionsForScaleSet {
    [CmdletBinding()]
    param(        
        [Parameter(Mandatory = $true)]
        [string]
        $ResourceGroupName,        
        [Parameter(Mandatory = $true)]
        [string]
        $KeyVaultName,
        [Parameter(Mandatory = $true)]
        [string]
        $ScaleSetName
    )
    process {
        Write-Verbose "Setting KeyVault policies for $ScaleSetName on $KeyVaultName ..."
        $VMSS = Get-AzVmss -ResourceGroupName $ResourceGroupName -VMScaleSetName $ScaleSetName -ErrorAction SilentlyContinue
        if (-not($VMSS)){
            Write-Verbose "Scale Set $ScaleSetName does not exists. Stopping here."
            return
        }
        $keyVault = Get-AzKeyVault -ResourceGroupName $ResourceGroupName -VaultName $KeyVaultName -ErrorAction SilentlyContinue         
        if (-not($keyVault)) {
            Write-Verbose "KeyVault $KeyVaultName does not exists. Stopping here."
            return
        }
        Set-AzKeyVaultAccessPolicy -VaultName $KeyVaultName -ResourceGroupName $ResourceGroupName -ObjectId $VMSS.Identity.PrincipalId -PermissionsToKeys get,list -PermissionsToSecrets get,list -PermissionsToCertificates get,list,getissuers,listissuers
        Write-Verbose "Done."
    }    
}