cloudflare-dns-cli/main.go

93 lines
1.8 KiB
Go
Raw Normal View History

2023-03-20 01:01:44 -04:00
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"net"
"os"
"github.com/libdns/cloudflare"
"github.com/libdns/libdns"
)
var (
domain = os.Getenv("DOMAIN")
token = os.Getenv("CF_TOKEN")
)
func main() {
ctx := context.TODO()
ip := net.IPv4(127, 0, 0, 1)
var cname string
sub := "<UNSET>"
var path string
flag.StringVar(&domain, "d", domain, "Domain name, e.g. example.com")
flag.StringVar(&sub, "s", sub, "Subdomain to add dns entry for, e.g. blog")
flag.StringVar(&token, "a", token, "Cloudflare API Token")
flag.TextVar(&ip, "i", ip, "IP address")
flag.StringVar(&cname, "c", cname, "CNAME target")
flag.StringVar(&path, "o", path, "path to save all records as json, e.g. ./records.json")
flag.Parse()
provider := cloudflare.Provider{APIToken: token}
zone := domain + "."
fmt.Println(zone, sub, cname)
setRecords := func() ([]libdns.Record, error) {
switch {
case cname != "":
return provider.SetRecords(ctx, zone, []libdns.Record{
{
Type: "CNAME",
Name: sub,
Value: cname,
},
})
case len(ip) == net.IPv4len:
return provider.SetRecords(ctx, zone, []libdns.Record{
{
Type: "A",
Name: sub,
Value: ip.To4().String(),
},
})
case len(ip) == net.IPv6len:
return provider.SetRecords(ctx, zone, []libdns.Record{
{
Type: "AAAA",
Name: sub,
Value: ip.To16().String(),
},
})
}
return nil, fmt.Errorf("neither cname nor valid ip is set")
}
if sub != "<UNSET>" {
newRecs, err := setRecords()
if err != nil {
fmt.Printf("%#v\n", err)
panic(err)
}
fmt.Println(newRecs)
}
if path != "" {
recs, err := provider.GetRecords(ctx, zone)
if err != nil {
panic(err)
}
data, err := json.Marshal(recs)
if err != nil {
panic(err)
}
err = os.WriteFile(path, data, 0644)
if err != nil {
panic(err)
}
}
}