---
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: {{ .dns.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: v1
kind: ConfigMap
metadata:
  name: coredns
  namespace: kube-system
  labels:
      addonmanager.kubernetes.io/mode: EnsureExists
data:
  Corefile: |
  {{- range .dns.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 | empty | not }}
      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 | empty | not }}
        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 $.dns.dns_etc_hosts | empty | not }}
      hosts /etc/coredns/hosts {
        fallthrough
      }
    {{- end }}
    }
  {{- end }}

{{- if .dns.coredns.dns_etc_hosts | empty | not }}
  hosts: |
  {{- range .dns.coredns.dns_etc_hosts }}
    {{ . }}
  {{- end }}
{{- end }}
