---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  labels:
    kubernetes.io/bootstrapping: rbac-defaults
    addonmanager.kubernetes.io/mode: Reconcile
  name: system:coredns
rules:
- apiGroups:
  - ""
  resources:
  - endpoints
  - services
  - pods
  - namespaces
  verbs:
  - list
  - watch
- apiGroups:
  - ""
  resources:
  - nodes
  verbs:
  - get
- apiGroups:
  - discovery.k8s.io
  resources:
  - endpointslices
  verbs:
  - list
  - watch

---
apiVersion: v1
kind: Service
metadata:
  name: coredns
  namespace: kube-system
  labels:
    k8s-app: kube-dns
    kubernetes.io/cluster-service: "true"
    kubernetes.io/name: "CoreDNS"
    addonmanager.kubernetes.io/mode: Reconcile
  annotations:
    prometheus.io/port: "9153"
    prometheus.io/scrape: "true"
    createdby: 'kubekey'
spec:
  clusterIP: {{ .kubernetes.networking.dns_service_ip }}
  selector:
    k8s-app: kube-dns
  ports:
    - name: dns
      port: 53
      protocol: UDP
    - name: dns-tcp
      port: 53
      protocol: TCP
    - name: metrics
      port: 9153
      protocol: TCP

---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: "coredns"
  namespace: kube-system
  labels:
    k8s-app: "kube-dns"
    addonmanager.kubernetes.io/mode: Reconcile
    kubernetes.io/name: "coredns"
spec:
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxUnavailable: 0
      maxSurge: 10%
  selector:
    matchLabels:
      k8s-app: kube-dns
  template:
    metadata:
      labels:
        k8s-app: kube-dns
      annotations:
        createdby: 'kubekey'
    spec:
      securityContext:
        seccompProfile:
          type: RuntimeDefault
      priorityClassName: system-cluster-critical
      serviceAccountName: coredns
      nodeSelector:
        kubernetes.io/os: linux
      tolerations:
        - key: node-role.kubernetes.io/master
          effect: NoSchedule
        - key: node-role.kubernetes.io/control-plane
          effect: NoSchedule
      affinity:
        podAntiAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
          - weight: 100
            podAffinityTerm:
              labelSelector:
                matchLabels:
                  k8s-app: kube-dns
              topologyKey: "kubernetes.io/hostname"
        nodeAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
          - weight: 100
            preference:
              matchExpressions:
              - key: node-role.kubernetes.io/control-plane
                operator: In
                values:
                - ""
      containers:
      - name: coredns
        image: "{{ .kubernetes.networking.dns_image }}"
        imagePullPolicy: IfNotPresent
        resources:
          # TODO: Set memory limits when we've profiled the container for large
          # clusters, then set request = limit to keep this container in
          # guaranteed class. Currently, this container falls into the
          # "burstable" category so the kubelet doesn't backoff from restarting it.
          limits:
            memory: 300Mi
          requests:
            cpu: 100m
            memory: 70Mi
        args: [ "-conf", "/etc/coredns/Corefile" ]
        volumeMounts:
        - name: config-volume
          mountPath: /etc/coredns
        ports:
        - containerPort: 53
          name: dns
          protocol: UDP
        - containerPort: 53
          name: dns-tcp
          protocol: TCP
        - containerPort: 9153
          name: metrics
          protocol: TCP
        securityContext:
          allowPrivilegeEscalation: false
          capabilities:
            add:
            - NET_BIND_SERVICE
            drop:
            - all
          readOnlyRootFilesystem: true
        livenessProbe:
          httpGet:
            path: /health
            port: 8080
            scheme: HTTP
          timeoutSeconds: 5
          successThreshold: 1
          failureThreshold: 10
        readinessProbe:
          httpGet:
            path: /ready
            port: 8181
            scheme: HTTP
          timeoutSeconds: 5
          successThreshold: 1
          failureThreshold: 10
      dnsPolicy: Default
      volumes:
        - name: config-volume
          configMap:
            name: coredns

---
apiVersion: v1
kind: ConfigMap
metadata:
  name: coredns
  namespace: kube-system
  labels:
      addonmanager.kubernetes.io/mode: EnsureExists
data:
  Corefile: |
  {{- range .kubernetes.coredns.zone_configs }}
    {{ .zones | join " " }} {
      cache {{ .cache }}
    {{- range .additional_configs }}
      {{ . }}
    {{- end }}

    {{- range .rewrite }}
      rewrite {{ .rule }} {
        {{ .field }} {{ .type }} {{ .value }}
        {{ .options }}
      }
    {{- end }}

      health {
        lameduck 5s
      }

    {{- if .kubernetes.zones | len | lt 0 }}
      kubernetes {{ .kubernetes.zones | join " " }} in-addr.arpa ip6.arpa {
        pods insecure
        fallthrough in-addr.arpa ip6.arpa
        ttl 30
      }
    {{- end }}

    {{- range .forward }}
      forward {{ .from }} {{ .to | join " " }} {
      {{- if .except | len | lt 0 }}
        except {{ .except | join " " }}
      {{- end }}
      {{- if .force_tcp }}
        force_tcp
      {{- end }}
      {{- if .prefer_udp }}
        prefer_udp
      {{- end }}
      {{- if .max_fails }}
        max_fails {{ .max_fails }}
      {{- end }}
      {{- if .expire }}
        expire {{ .expire }}
      {{- end }}
      {{- if .tls }}
        tls {{ .tls.cert_file }} {{ .tls.key_file }} {{ .tls.ca_file }}
      {{- end }}
      {{- if .tls_servername }}
        tls_servername {{ .tls_servername }}
      {{- end }}
      {{- if .policy }}
        policy {{ .policy }}
      {{- end }}
      {{- if .health_check }}
        health_check {{ .health_check }}
      {{- end }}
      {{- if .max_concurrent }}
        max_concurrent {{ .max_concurrent }}
      {{- end }}
      }
    {{- end }}

    {{- if $.kubernetes.coredns.dns_etc_hosts | len | lt 0 }}
      hosts /etc/coredns/hosts {
        fallthrough
      }
    {{- end }}
    }
  {{- end }}

{{- if .kubernetes.coredns.dns_etc_hosts | len | lt 0 }}
  hosts: |
  {{- range .kubernetes.coredns.dns_etc_hosts }}
    {{ . }}
  {{- end }}
{{- end }}
