Idempotently set upstream nameservers in dns addon

I’m running an old version of microk8s (1.18), and need update the DNS nameserver to Azure’s one so that my Private Link connection resolves correctly. Newer versions support enable dns:1.2.3.4 but alas I’m one version behind and am not in a place where I can upgrade.

Changing the DNS after the fact is easy enough to do via microk8s kubectl -n kube-system edit configmap/coredns and editting out the 8.8.8.8, 8.8.4.4:

apiVersion: v1
data:
  Corefile: |
    .:53 {
        errors
        health {
          lameduck 5s
        }
        ready
        log . {
          class error
        }
        kubernetes cluster.local in-addr.arpa ip6.arpa {
          pods insecure
          fallthrough in-addr.arpa ip6.arpa
        }
        prometheus :9153
        forward . 168.63.129.16
        cache 30
        loop
        reload
        loadbalance
    }
kind: ConfigMap

However I don’t see how I could do this programmatically (i.e. via Ansible). Can I create this ConfigMap file somewhere and tell microk8s to use it? I can’t find any configuration/yaml in /var/snap that relates to this change.

I’m very new to Kubernetes so apologies in advance if I’m asking something obvious. I need to be able to do this programmatically so I can apply the same steps across multiple environments.

Hi you can try some of the techniques diacussed here, such as exporting the yaml using kubectl get cm | sed. ... | kubectl apply -f - ....

Awesome, thanks for the pointers!

I’ve now created a simple Ansible playbook to do this for me, sharing below in case it’s useful for others:

---
- name: Update coredns nameservers
  hosts: jupyter
  vars:
    nameservers: 168.63.129.16 # Azure

  tasks:
  - name: Read coredns configmap
    command: microk8s kubectl get configmap/coredns -n kube-system -o yaml
    register: coredns_config_stdout
    changed_when: no
    become: yes
    become_user: "{{ app_user }}"

  - name: Parse configmap yaml into usable variable
    set_fact:
      coredns_config: "{{ coredns_config_stdout.stdout | from_yaml }}"

  - name: Replace 'forward' nameservers with our config
    set_fact:
      new_coredns_config:
        data:
          Corefile: "{{ coredns_config.data.Corefile | regex_replace('forward \\. ([0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+ *)+\\n', 'forward . ' + nameservers + ' \\n' ) }}"

  - name: Create coredns configmap file
    copy:
      content: "{{ coredns_config | combine(new_coredns_config) | to_yaml }}"
      dest: "/home/{{ app_user }}/coredns.configmap.yaml"
    become: yes
    when: coredns_config.data.Corefile != new_coredns_config.data.Corefile

  - name: Load in new coredns configmap
    command: microk8s kubectl apply -f "/home/{{ app_user }}/coredns.configmap.yaml"
    when: coredns_config.data.Corefile != new_coredns_config.data.Corefile
    become: yes
    become_user: "{{ app_user }}"
1 Like