Initial commit

This commit is contained in:
Balakrishnan Balasubramanian 2023-03-20 01:01:44 -04:00
commit 89a8a36b51
3 changed files with 105 additions and 0 deletions

8
go.mod Normal file
View File

@ -0,0 +1,8 @@
module go.balki.me/cloudflaredns
go 1.20
require (
github.com/libdns/cloudflare v0.1.0
github.com/libdns/libdns v0.2.1
)

5
go.sum Normal file
View File

@ -0,0 +1,5 @@
github.com/libdns/cloudflare v0.1.0 h1:93WkJaGaiXCe353LHEP36kAWCUw0YjFqwhkBkU2/iic=
github.com/libdns/cloudflare v0.1.0/go.mod h1:a44IP6J1YH6nvcNl1PverfJviADgXUnsozR3a7vBKN8=
github.com/libdns/libdns v0.2.0/go.mod h1:yQCXzk1lEZmmCPa857bnk4TsOiqYasqpyOEeSObbb40=
github.com/libdns/libdns v0.2.1 h1:Wu59T7wSHRgtA0cfxC+n1c/e+O3upJGWytknkmFEDis=
github.com/libdns/libdns v0.2.1/go.mod h1:yQCXzk1lEZmmCPa857bnk4TsOiqYasqpyOEeSObbb40=

92
main.go Normal file
View File

@ -0,0 +1,92 @@
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)
}
}
}