Search code examples
kuberneteskubernetes-operatorkubernetes-dns

How to update DNS configuration of K8S Pod


I had a project that wanted to update the DNS configuration of Pod with Operator,

get dns message
get matched pod
modify:
    pod.Spec.DNSConfig = CRD_SPEC
    pod.Spec.DNSPolicy = corev1.DNSNone
client.Update(ctx,&pod)

But when I implemented it, I got the following error:

 ERROR   controller-runtime.manager.controller.dnsinjection      Reconciler error        {"reconciler group": "xxxx", "reconciler kind": "xxxxx", "name": "dnsinjection", "namespace": "default", "error": "Pod \"busybox\" is invalid: spec: Forbidden: pod updates may not change fields other than `spec.containers[*].image`, `spec.initContainers[*].image`, `spec.activeDeadlineSeconds` or `spec.tolerations` (only additions to existing tolerations)\n  core.PodSpec{\n  \t... // 21 identical fields\n  \tPriority:         &0,\n  \tPreemptionPolicy: nil,\n  \tDNSConfig: &core.PodDNSConfig{\n  \t\tNameservers: []string{\n  \t\t\t\"1.2.3.4\",\n- \t\t\t\"0.0.0.0\",\n  \t\t},\n  \t\tSearches: []string{\"ns1.svc.cluster-domain.example\", \"my.dns.search.suffix\"},\n  \t\tOptions:  []core.PodDNSConfigOption{{Name: \"ndots\", Value: &\"2\"}, {Name: \"edns0\"}},\n  \t},\n  \tReadinessGates:   nil,\n  \tRuntimeClassName: nil,\n  \t... // 3 identical fields\n  }\n"}

DNSConfig and DNSPoicy fields are not declared to be unable to be updated in the source code, so why did the update fail?

I got the same error with kubect edit pod busybox and kubectl apply -f modifyed_pod.yml(add DNSConfig) command.

I would appreciate it if you could tell me how to solve it.


Solution

  • Like the message says you cannot update a DNS config of a pod: Forbidden: pod updates may not change fields other than spec.containers[*].image, spec.initContainers[*].image.

    If you want to inject a DNS config into all pods you need to add the configuration before the pod is created. Look into MutatingAdmissionWebhook as an approach for this.