How to assign a namespace to certain nodes?

To achieve this you can use PodNodeSelector admission controller.

First, you need to enable it in your kubernetes-apiserver:

  • Edit /etc/kubernetes/manifests/kube-apiserver.yaml:
    • find --enable-admission-plugins=
    • add PodNodeSelector parameter

Now, you can specify scheduler.alpha.kubernetes.io/node-selector option in annotations for your namespace, example:

apiVersion: v1
kind: Namespace
metadata:
 name: your-namespace
 annotations:
   scheduler.alpha.kubernetes.io/node-selector: env=test
spec: {}
status: {}

After these steps, all the pods created in this namespace will have this section automatically added:

nodeSelector
  env: test

More information about the PodNodeSelector you can find in the official Kubernetes documentation: https://kubernetes.io/docs/reference/access-authn-authz/admission-controllers/#podnodeselector


kubeadm users

If you deployed your cluster using kubeadm and if you want to make this configuration persistent, you have to update your kubeadm config file:

kubectl edit cm -n kube-system kubeadm-config

specify extraArgs with custom values under apiServer section:

apiServer: 
  extraArgs: 
    enable-admission-plugins: NodeRestriction,PodNodeSelector

then update your kube-apiserver static manifest on all control-plane nodes:

# Kubernetes 1.22 and forward:
kubectl get configmap -n kube-system kubeadm-config -o=jsonpath="{.data}" > kubeadm-config.yaml

# Before Kubernetes 1.22:
# "kubeadmin config view" was deprecated in 1.19 and removed in 1.22
# Reference: https://github.com/kubernetes/kubeadm/issues/2203
kubeadm config view > kubeadm-config.yaml

# Update the manifest with the file generated by any of the above lines 
kubeadm init phase control-plane apiserver --config kubeadm-config.yaml

kubespray users

You can just use kube_apiserver_enable_admission_plugins variable for your api-server configuration variables:

 kube_apiserver_enable_admission_plugins:
   - PodNodeSelector

I totally agree with the @kvaps answer but something is missing : it is necessary to add a label in your node :

kubectl label node <yournode> env=test

Like that, the pod created in the namespace with scheduler.alpha.kubernetes.io/node-selector: env=test will be schedulable only on node with env=test label

Tags:

Kubernetes