Skip to content

Instantly share code, notes, and snippets.

@denzhel
Last active June 30, 2021 06:48
Show Gist options
  • Select an option

  • Save denzhel/2dc4e6ac3f19195fcb8e9b6d32f19459 to your computer and use it in GitHub Desktop.

Select an option

Save denzhel/2dc4e6ac3f19195fcb8e9b6d32f19459 to your computer and use it in GitHub Desktop.
Limit number of K8s namespaces per user

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment