Listing Security Groups for an AKS Namespace

The following Bash script will help you to retrieve the security groups that are associated with an AKS namespace. I recently needed this when assuming responsibility for an existing namespace for which I needed to add new authorized users.

If a namespace is provided at the commandline, (ex: getnsgroup mynamespace), then it will use the provided namespace for each kubectl command. If no namespace is provided, then it will attempt to retrieve the namespace from the current context.

#!/bin/bash

if [ $# -eq 0 ]; then
  # if no namespace was passed, then get the currently selected namespace
  ns=$(kubectl config get-contexts | awk '$1 == "*" {print $5}')
else
  ns=$1
fi

# get the rolebinding for the response matching ROLE = "Role/edit"
rb=$(kubectl get rolebinding -n $ns | awk '$2 == "Role/edit" {print $1}')

# get the subject 'name' value where apiGroup is 'rbac.authorization.k8s.io'
gids=$(kubectl get rolebinding $rb -n $ns -o json | \
    jq -r '.subjects[] | select(.apiGroup == "rbac.authorization.k8s.io" and .kind == "Group") | .name')

# query Azure AD for the group matching that id and show the displayname. Note that you must have the 
# azure cli installed for this to work.
for gid in $gids; do
    # Get the display name.  If it doesn't exist, or if an error occurs, then set it to "Not found"
    displayName=$(az ad group show --group $gid --query 'displayName' -o tsv 2>/dev/null)
    if [ -z "$displayName" ]; then
        displayName="Not found"
    fi
    echo "Group ID: $gid, Display Name: $displayName"
done