Update Node Selector field for PODs on the fly

3/26/2019

I have been trying different things around k8s these days. I am wondering about the field nodeSelector in the POD specification. As I understand we have to assign some labels to the nodes and these labels can further be used in the nodeSelector field part of the POD specification.

Assignment of the node to pods based on nodeSelector works fine. But, after I create the pod, now I want to update/overwrite the nodeSelector field which would deploy my pod to new node based on new nodeSelector label updated.

I am thinking this in the same way it is done for the normal labels using kubectl label command.

Are there any hacks to achieve such a case ?

If this is not possible for the current latest versions of the kubernetes, why should not we consider it ?

Thanks.

-- Pert8S
kubectl
kubernetes
pod

1 Answer

3/26/2019

While editing deployment manually as cookiedough suggested is one of the options, I believe using kubctl patch would be a better solution.

You can either patch by using yaml file or JSON string, which makes it easier to integrate thing into scripts. Here is a complete reference.


Example

Here's a simple deployment of nginx I used, which will be created on node-1:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.7.9
        ports:
        - containerPort: 80
      nodeSelector:
        kubernetes.io/hostname: node-1

JSON patch

You can patch the deployment to change the desired node as follows:
kubectl patch deployments nginx-deployment -p '{"spec": {"template": {"spec": {"nodeSelector": {"kubernetes.io/hostname": "node-2"}}}}}'

YAML patch

By running kubectl patch deployment nginx-deployment --patch "$(cat patch.yaml)", where patch.yaml is prepared as follows:

spec:
  template:
    spec:
      nodeSelector:
        kubernetes.io/hostname: node-2

Both will result in scheduler scheduling new pod on requested node, and terminating the old one as soon as the new one is ready.

-- MWZ
Source: StackOverflow