-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsync2cloudflare.go
97 lines (89 loc) · 2.46 KB
/
sync2cloudflare.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package cfnssync
import (
"context"
"log/slog"
"os"
"strings"
"github.com/cloudflare/cloudflare-go"
"github.com/samber/lo"
)
const (
cfToken = "CLOUDFLARE_API_TOKEN"
cfZone = "CLOUDFLARE_ZONE_NAME"
)
var api *cloudflare.API
var (
cfZoneName string
cfZoneID string
cfZoneIdent *cloudflare.ResourceContainer
)
func InitCloudflare(ctx context.Context) error {
var err error
token := os.Getenv(cfToken)
api, err = cloudflare.NewWithAPIToken(token)
if err != nil {
return err
}
cfZoneName = os.Getenv(cfZone)
cfZoneID, err = api.ZoneIDByName(cfZoneName)
if err != nil {
return err
}
cfZoneIdent = cloudflare.ZoneIdentifier(cfZoneID)
return nil
}
func Sync2Cloudflare(ctx context.Context, name, content string) {
slog.InfoContext(ctx, "start sync to cloudflare", "name", name, "content", content)
if api == nil || cfZoneIdent == nil {
slog.ErrorContext(ctx, "cloudflare api not initilized")
return
}
if !strings.HasSuffix(name, cfZoneName) {
slog.InfoContext(ctx, "zone name not matched", "expect", cfZoneName, "got", name)
return
}
records, _, err := api.ListDNSRecords(ctx, cfZoneIdent, cloudflare.ListDNSRecordsParams{})
if err != nil {
slog.ErrorContext(ctx, "ListDNSRecords fail", "err", err.Error())
return
}
rec, ok := lo.Find(records, func(rr cloudflare.DNSRecord) bool {
return rr.Name == name
})
priority := uint16(10)
proxied := false
const ttl = 300 // seconds
if !ok {
// should create new record
if _, err := api.CreateDNSRecord(ctx, cfZoneIdent, cloudflare.CreateDNSRecordParams{
Type: "A",
Name: name,
Content: content,
TTL: ttl,
Priority: &priority,
Proxied: &proxied,
}); err != nil {
slog.ErrorContext(ctx, "CreateDNSRecord fail", "name", name, "content", content, "err", err.Error())
return
}
slog.InfoContext(ctx, "CreateDNSRecord success", "name", name, "content", content)
return
}
if rec.Content == content {
slog.InfoContext(ctx, "record already exists and has the same content", "name", name, "content", content)
return
}
// should update record content
if _, err := api.UpdateDNSRecord(ctx, cfZoneIdent, cloudflare.UpdateDNSRecordParams{
Type: "A",
Name: name,
Content: content,
TTL: ttl,
Proxied: &proxied,
ID: rec.ID,
}); err != nil {
slog.ErrorContext(ctx, "UpdateDNSRecord fail", "name", name, "content", content, "err", err.Error())
return
}
slog.InfoContext(ctx, "CreateDNSRecord success", "name", name, "content", content)
}