diff --git a/hack/generate_dns_records/dnsrecord.yaml.tmpl b/hack/generate_dns_records/dnsrecord.yaml.tmpl new file mode 100644 index 00000000..79d2f79d --- /dev/null +++ b/hack/generate_dns_records/dnsrecord.yaml.tmpl @@ -0,0 +1,26 @@ +--- +apiVersion: cloudflare-operator.io/v1 +kind: DNSRecord +metadata: + name: {{ .Name | cleanName }} +spec: + name: {{ .Name }} + proxied: true + ttl: {{ .TTL }} + type: {{ .Type }} +{{- if and (ne .Type "SRV") (ne .Type "MX") }} + content: {{ .Content | trimDot }} +{{- end }} +{{- if (eq .Type "SRV") }} + {{- $d := split .Content " " }} + data: + priority: {{ index $d 0 }} + weight: {{ index $d 1 }} + port: {{ index $d 2 }} + target: {{ index $d 3 | trimDot }} +{{- end }} +{{- if (eq .Type "MX") }} +{{ $d := split .Content " " }} + priority: {{ index $d 0 }} + content: {{ index $d 1 | trimDot }} +{{- end }} diff --git a/hack/generate_dns_records/go.mod b/hack/generate_dns_records/go.mod new file mode 100644 index 00000000..f8c088b1 --- /dev/null +++ b/hack/generate_dns_records/go.mod @@ -0,0 +1,3 @@ +module github.com/containeroo/generate-dns-records + +go 1.23.1 diff --git a/hack/generate_dns_records/main.go b/hack/generate_dns_records/main.go new file mode 100644 index 00000000..a6461559 --- /dev/null +++ b/hack/generate_dns_records/main.go @@ -0,0 +1,82 @@ +package main + +import ( + "flag" + "os" + "regexp" + "strings" + "text/template" +) + +type DNSRecord struct { + Name string + Type string + TTL string + Content string +} + +var zonefilePath string + +func init() { + flag.StringVar(&zonefilePath, "file", "", "Path to the exported zonefile") + flag.Parse() +} + +func main() { + zonefile, err := os.ReadFile(zonefilePath) + if err != nil { + panic(err) + } + + zonefileParseRegex := `(.*)\s(\d+)\sIN\s([A-Z]+)\s(.*)` + + regex := regexp.MustCompile(zonefileParseRegex) + + var records []DNSRecord + + for _, line := range strings.Split(string(zonefile), "\n") { + if match := regex.MatchString(line); match { + name := strings.TrimSuffix(regex.FindStringSubmatch(line)[1], ".") + ttl := regex.FindStringSubmatch(line)[2] + recordType := regex.FindStringSubmatch(line)[3] + content := regex.FindStringSubmatch(line)[4] + + if recordType == "SOA" || recordType == "NS" { + continue + } + + record := DNSRecord{ + Name: name, + Type: recordType, + TTL: ttl, + Content: content, + } + + records = append(records, record) + } + } + + funcMap := template.FuncMap{ + "split": strings.Split, + "trimDot": func(s string) string { + return strings.TrimSuffix(s, ".") + }, + "cleanName": func(s string) string { + noDots := strings.ReplaceAll(s, ".", "-") + noUnderscores := strings.ReplaceAll(noDots, "_", "-") + return noUnderscores + }, + } + + for _, record := range records { + tmplFile := "dnsrecord.yaml.tmpl" + tmpl, err := template.New(tmplFile).Funcs(funcMap).ParseFiles(tmplFile) + if err != nil { + panic(err) + } + err = tmpl.Execute(os.Stdout, record) + if err != nil { + panic(err) + } + } +}