-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupdate.go
128 lines (100 loc) · 2.67 KB
/
update.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package main
import (
"context"
"errors"
"fmt"
"log"
"git.leon.wtf/leon/new-cfupdater/config"
"github.com/cloudflare/cloudflare-go"
)
type version int
const (
v4 version = iota
v6
)
var zoneIDs = make(map[string]string)
func GetAllZoneIDs() error {
for zone := range conf.Zones {
zoneID, err := cfAPI.ZoneIDByName(zone)
if err != nil {
return err
}
zoneIDs[zone] = zoneID
}
return nil
}
func update(v version, newIP string) error {
for confZone, confRecords := range conf.Zones {
zoneID := zoneIDs[confZone]
for _, confRecord := range confRecords {
// evaluate record type
var recType string
if v == v4 && confRecord.UpdateIPv4 {
recType = "A"
} else if v == v6 && confRecord.UpdateIPv6 {
recType = "AAAA"
} else {
// record type should not be updated
continue
}
// get matching record(s) for the zone
records, err := cfAPI.DNSRecords(context.Background(), zoneID, cloudflare.DNSRecord{
Type: recType,
Name: confRecord.Name,
})
if err != nil {
return err
}
if l := len(records); l == 0 {
// record does not exits
// create if record.Create = true
if !confRecord.Create {
log.Printf("Update of record %s %s (Zone: %s) skipped (does not exist and key \"create\" is false)\n", recType, confRecord.Name, confZone)
continue
}
proxied := confRecord.Proxy == config.ProxyActivate // config.ProxyPreserve means false by default !!!
resp, err := cfAPI.CreateDNSRecord(context.Background(), zoneID, cloudflare.DNSRecord{
Type: recType,
Name: confRecord.Name,
Content: newIP,
TTL: 1, // automatic
Proxied: &proxied,
})
if err != nil {
return err
}
if !resp.Success {
return fmt.Errorf("error while adding DNS record: %v", resp.Errors)
}
} else if l == 1 {
thisRecord := records[0]
newRecord := thisRecord
// change existing record and push
newRecord.Content = newIP
if confRecord.Proxy != config.ProxyPreserve {
proxied := confRecord.Proxy == config.ProxyActivate
newRecord.Proxied = &proxied
} // else leave newRecord.Proxied untouched ("ProxyPreserve")
if err := cfAPI.UpdateDNSRecord(context.Background(), zoneID, thisRecord.ID, newRecord); err != nil {
return err
}
} else {
return errors.New("got more than one record")
}
}
var updatedVersion string
if v == v4 {
updatedVersion = "IPv4"
} else {
updatedVersion = "IPv6"
}
log.Printf("%s updates for zone %s successfull", updatedVersion, confZone)
}
return nil
}
func UpdateIPv4(newIP string) error {
return update(v4, newIP)
}
func UpdateIPv6(newIP string) error {
return update(v6, newIP)
}