We use a wrapper script to allow the developers to fire up K8s namespaces with all the deployments. Sometimes, they exaggerate and open a lot of them.
I wrote this function to limit the number of namespaces they can open. The scripts assumes each namespaces has a label with the owner tag.
function limit_namespaces_per_user() {
# Define the user and how many namespaces to allow per user
local ALLOWED_NS="${1}"
local NS_OWNER=$(whoami)
# Extract a list of namespaces with only the owner annotation
# Exclude travis and <none> namespaces from this limitation, delete empty lines,
# make it a one liner and count the number of namespaces
local NS_PER_OWNER=$(kubectl \
get \
namespaces \
--no-headers \
-o custom-columns="OWNER":".metadata.annotations.<SomeIdentifinerLikeOrgName>/ns-owner" \
| sed 's/travis//g;s/<none>//g;/^$/d' \
| tr '\n' ' ' \
| awk '{print gsub(/'"${NS_OWNER}"'/, "")}')
# Check how many namespaces a user has
if (( "${NS_PER_OWNER}" >= "${ALLOWED_NS}" )); then
echo "ERROR: ${NS_OWNER}, the number of allowed namespaces per user is ${ALLOWED_NS}"
exit 1
fi
}
#k8s #kubernetes