Skip to content

Instantly share code, notes, and snippets.

@slmcmahon
Last active June 20, 2025 18:37
Show Gist options
  • Save slmcmahon/ee29b25b80b180e1ba6ae0049a435d77 to your computer and use it in GitHub Desktop.
Save slmcmahon/ee29b25b80b180e1ba6ae0049a435d77 to your computer and use it in GitHub Desktop.
Displays the security groups that are associated with an AKS namespace
function Get-CurrentContext {
# Get the output of 'kubectl config get-contexts' and convert it to a string array
$contexts = kubectl config get-contexts | Out-String -Stream
# Split the output into lines and remove empty lines
$lines = $contexts | Where-Object { $_.Trim() -ne "" }
# Parse the header to determine column positions
$headerLine = $lines[0]
$headerParts = $headerLine -split '\s+'
$namespaceIndex = $headerParts.IndexOf('NAMESPACE')
# Parse each line after the header
for ($i = 1; $i -lt $lines.Count; $i++) {
$line = $lines[$i] -split '\s+'
if ($line[0] -eq '*') {
$currentNamespace = $line[$namespaceIndex]
break
}
}
# Output the current namespace
$currentNamespace
}
function Get-RoleBinding {
param ([string]$ns)
# Get the output of 'kubectl get rolebinding -n $ns'
$output = kubectl get rolebinding -n $ns | Out-String -Stream
# Split the output into lines and remove empty lines
$lines = $output | Where-Object { $_.Trim() -ne "" }
# Parse the header line to determine column positions
$headerLine = $lines[0]
$headerParts = $headerLine -split '\s+'
$roleIndex = $headerParts.IndexOf('ROLE')
# Initialize an array to hold the matching names
$matchingNames = @()
# Parse each line after the header
for ($i = 1; $i -lt $lines.Count; $i++) {
$line = $lines[$i] -split '\s{2,}' # Split by at least two spaces to handle multi-word columns
if ($line[$roleIndex] -eq "Role/edit") {
$matchingNames += $line[0]
}
}
# Output the matching names
$matchingNames
}
function Get-RoleBindingGroupIds {
param ([string]$rb, [string]$ns)
$jsonOutput = kubectl get rolebinding $rb -n $ns -o json | ConvertFrom-Json
$gids = $jsonOutput.subjects | Where-Object { $_.apiGroup -eq "rbac.authorization.k8s.io" -and $_.kind -eq "Group" } | Select-Object -ExpandProperty name
$gids
}
function main() {
Import-Module AzureAD
Connect-AzureAD
param ([Parameter(Mandatory = $false)][string]$ns = (Get-CurrentContext))
$rb = Get-RoleBinding -ns $ns
$gids = Get-RoleBindingGroupIds -rb $rb -ns $ns
foreach ($gid in $gids) {
try {
# Get the display name
$group = Get-AzADGroup -ObjectId $gid -ErrorAction Stop
$displayName = $group.DisplayName
} catch {
# If an error occurs, set displayName to "Not found"
$displayName = "Not found"
}
# If displayName is empty, set it to "Not found"
if ([string]::IsNullOrEmpty($displayName)) {
$displayName = "Not found"
}
# Output the result
Write-Output "Group ID: $gid, Display Name: $displayName"
}
}
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment