Skip to content

Commit

Permalink
Add code to create a new DNS record if it doesn't exist on startup.
Browse files Browse the repository at this point in the history
  • Loading branch information
joshuar committed Feb 26, 2023
1 parent 5ba54e9 commit ad28465
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 4 deletions.
2 changes: 0 additions & 2 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,6 @@ var rootCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
cfDetails := cloudflare.NewCloudflare()

cfDetails.CheckAndUpdate()

ticker := time.NewTicker(getIntervalFromConfig())
done := make(chan bool)
for {
Expand Down
45 changes: 43 additions & 2 deletions internal/cloudflare/cloudflare.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ func NewCloudflare() *cloudflare {
record := make(map[string]*dnsRecord)

for _, r := range getRecordsFromConfig() {
log.Debugf("Getting DNS records for %s", r)
log.Debugf("Getting DNS record(s) for %s", r)
recs, _, err := api.ListDNSRecords(
ctx,
cf.ZoneIdentifier(id),
Expand All @@ -69,7 +69,48 @@ func NewCloudflare() *cloudflare {
}
}
} else {
log.Warnf("Record %s has no matching details in Cloudflare zone", r)
log.Warnf("%s has no matching DNS record(s) in Cloudflare zone, creating a new one", r)
addr := iplookup.LookupExternalIP()
if addr.Ipv4 != "" {
res, err := api.CreateDNSRecord(
ctx,
cf.ZoneIdentifier(id),
cf.CreateDNSRecordParams{
Name: r,
Content: addr.Ipv4,
Type: "A",
})
if err != nil {
log.Warnf("Unable to create new IPv4 record for %s: %v", r, err)
} else {
log.Infof("Created new IPv4 record for %s", r)
}
record[res.Result.ID] = &dnsRecord{
name: res.Result.Name,
IpAddr: res.Result.Content,
recordType: res.Result.Type,
}
}
if addr.Ipv6 != "" {
res, err := api.CreateDNSRecord(
ctx,
cf.ZoneIdentifier(id),
cf.CreateDNSRecordParams{
Name: r,
Content: addr.Ipv6,
Type: "AAAA",
})
if err != nil {
log.Warnf("Unable to create new IPv4 record for %s: %v", r, err)
} else {
log.Infof("Created new IPv4 record for %s", r)
}
record[res.Result.ID] = &dnsRecord{
name: res.Result.Name,
IpAddr: res.Result.Content,
recordType: res.Result.Type,
}
}
}
}

Expand Down

0 comments on commit ad28465

Please sign in to comment.