Skip to content

Commit

Permalink
feat: add dns record generator
Browse files Browse the repository at this point in the history
  • Loading branch information
rxbn committed Sep 25, 2024
1 parent 5d9e568 commit feaf25b
Show file tree
Hide file tree
Showing 3 changed files with 111 additions and 0 deletions.
26 changes: 26 additions & 0 deletions hack/generate_dns_records/dnsrecord.yaml.tmpl
Original file line number Diff line number Diff line change
@@ -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 }}
3 changes: 3 additions & 0 deletions hack/generate_dns_records/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/containeroo/generate-dns-records

go 1.23.1
82 changes: 82 additions & 0 deletions hack/generate_dns_records/main.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
}

0 comments on commit feaf25b

Please sign in to comment.