Convert existing namespace to subnamespace using Hierarchial Namespace Controller

The Hierachial Namespace Controller is great for simplifying managing multiple namespaces that can be grouped together, but what if you already have all your namespaces created and being used? Since Kubernetes is declarative we can update the existing namespaces and add configuration to tell the controller what we are trying to do.

If you have the kubectl-hns plugin installed you can see a hierarchial tree view of all namespaces. Initially it will appear flat.

$ kubectl hns tree --all-namespaces

# pepperoni
# pizzeria

To change and convert a namespace to become a subnamespace we need to create a relationship between them. This can be done with an annotation and a CustomResourceDefinition called a SubnamespaceAnchor.

If those commands run successfully then the hierarchial tree view of all namespaces should now show the child namespace as a subnamespace of the parent.

$ kubectl hns tree --all-namespaces

# pizzeria
# └── [s] pepperoni
#
# [s] indicates subnamespaces

If you do not create the SubnamespaceAnchor in the namespace that was just annotated as a subnamespace, you may see a SubnamespaceAnchorMissing error when running kubectl hns commands.

pizzeria
# └── [s] pepperoni (1)
#
# [s] indicates subnamespaces
#
# Conditions:
# 1) BadConfiguration (SubnamespaceAnchorMissing): The anchor is missing in the parent namespace

If you try and create the SubnamespaceAnchor without adding the annotation you may see an error from the admission controller.

Error from server (Conflict): error when creating "STDIN": admission webhook "subnamespaceanchors.hnc.x-k8s.io" denied the request: Operation cannot be fulfilled on subnamespaceanchors.hnc.x-k8s.io "pepperoni": cannot create a subnamespace using an existing namespace

Add comment