diff --git a/netbox-dns-updater.go b/netbox-dns-updater.go index a226247..99d8ad8 100644 --- a/netbox-dns-updater.go +++ b/netbox-dns-updater.go @@ -7,8 +7,10 @@ import ( "io" "log" "net/http" + "net/url" "os" "os/exec" + "path" "strings" ) @@ -21,8 +23,10 @@ type NetBoxResponse struct { Results []IPAddress `json:"results"` } -func FetchNetboxIPAddresses(apiURL, token string) ([]IPAddress, error) { - req, err := http.NewRequest("GET", apiURL, nil) +func FetchNetboxIPAddresses(apiBaseURL, token string) ([]IPAddress, error) { + u, _ := url.Parse(apiBaseURL) + u.Path = path.Join(u.Path, "ipam/ip-addresses") + req, err := http.NewRequest("GET", u.String(), nil) if err != nil { return nil, err } @@ -57,7 +61,7 @@ func FetchNetboxIPAddresses(apiURL, token string) ([]IPAddress, error) { return filtered, nil } -func CreateDnsMasqConfig() { +func CreateDnsMasqConfig(writeConfig bool) { token := os.Getenv("NETBOX_TOKEN") if token == "" { home := os.Getenv("HOME") @@ -77,13 +81,13 @@ func CreateDnsMasqConfig() { } } - ips, err := FetchNetboxIPAddresses(apiURL, token) + ips, err := FetchNetboxIPAddresses(apiBaseURL, token) if err != nil { log.Fatalf("Error fetching IP addresses: %v", err) } dir := "/etc/dnsmasq.d" - if stat, err := os.Stat(dir); err == nil && stat.IsDir() { + if stat, err := os.Stat(dir); err == nil && stat.IsDir() && !writeConfig { file, err := os.Create(dir + "/netbox.conf") if err != nil { log.Fatalf("Failed to create netbox.conf: %v", err) @@ -99,20 +103,27 @@ func CreateDnsMasqConfig() { } } -var apiURL string +var apiBaseURL string func main() { listenAddr := flag.String("listen", ":8080", "address and port to listen on (e.g. :8080 or 127.0.0.1:8080)") - flag.StringVar(&apiURL, "api-url", "https://netbox.koszewscy.waw.pl/api/ipam/ip-addresses/", "NetBox API URL to fetch IP addresses") + flag.StringVar(&apiBaseURL, "api-url", "https://netbox.koszewscy.waw.pl/api", "NetBox API URL to fetch IP addresses") + dryRun := flag.Bool("dry-run", false, "if set, do not write to dnsmasq config file, just print the output") flag.Parse() + if *dryRun { + log.Println("Dry run mode enabled, not writing to dnsmasq config file.") + CreateDnsMasqConfig(true) + return + } + http.HandleFunc("/update-dnsmasq", func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet { w.WriteHeader(http.StatusMethodNotAllowed) w.Write([]byte("Method not allowed")) return } - CreateDnsMasqConfig() + CreateDnsMasqConfig(false) cmd := exec.Command("systemctl", "restart", "dnsmasq.service") if err := cmd.Run(); err != nil { log.Printf("Failed to restart dnsmasq.service: %v", err)