ipam/cmd/import.go

80 lines
1.8 KiB
Go
Raw Permalink Normal View History

2023-03-10 17:52:20 +01:00
/*
Copyright © 2023 Laura Kalb <dev@lauka.net>
*/
package cmd
import (
2023-03-31 20:13:55 +02:00
"encoding/json"
"fmt"
"os"
"path"
"time"
2023-03-10 17:52:20 +01:00
2023-03-31 20:13:55 +02:00
"github.com/spf13/cobra"
2023-03-10 17:52:20 +01:00
)
var importCmd = &cobra.Command{
2023-03-31 20:13:55 +02:00
Use: "import",
Short: "Import ipam configuration",
Long: `Import subnets to ipam.`,
Example: "ipam import --file import.json",
Args: cobra.NoArgs,
Aliases: []string{"im"},
Run: func(cmd *cobra.Command, args []string) {
var importname string
var subnets []Subnet
2023-03-24 16:27:45 +01:00
2023-03-31 20:13:55 +02:00
flagpath, _ := cmd.Flags().GetString("file")
if path.IsAbs(flagpath) {
importname = flagpath
} else {
wd, _ := os.Getwd()
importname = path.Join(wd, flagpath)
}
2023-03-24 16:27:45 +01:00
2023-03-31 20:13:55 +02:00
file, readerr := os.ReadFile(importname)
if readerr != nil {
fmt.Printf("[ERROR] Can't read file %v\n", importname)
fmt.Println(readerr)
}
2023-03-24 16:27:45 +01:00
2023-03-31 20:13:55 +02:00
marsherr := json.Unmarshal(file, &subnets)
if marsherr != nil {
fmt.Printf("[ERROR] Invalid format for file %v\n", importname)
fmt.Println(marsherr)
}
2023-03-24 16:27:45 +01:00
2023-03-31 20:13:55 +02:00
for _, subnet := range subnets {
fmt.Printf("[INFO] Start import of %v\n", subnet.Subnet.String())
subnet.ChangedBy = "ipam import"
subnet.ChangedAt = time.Now()
2023-03-24 16:27:45 +01:00
2023-03-31 20:13:55 +02:00
for _, addr := range subnet.Addresses {
addr.ChangedBy = "ipam import"
addr.ChangedAt = time.Now()
if addr.FQDN != "" {
err := AddDNSFqdn(addr.FQDN, addr.IP)
if err != nil {
fmt.Printf("[ERROR] %v\n", err)
}
}
}
2023-03-24 16:27:45 +01:00
2023-03-31 20:13:55 +02:00
suberr := subnet.WriteSubnet()
if suberr != nil {
fmt.Printf("[ERROR] Can't write subnet to file %v\n", subnet.Subnet.String())
fmt.Println(suberr)
}
fmt.Printf("[INFO] Imported subnet %v successfully\n", subnet.Subnet.String())
2023-03-24 16:27:45 +01:00
2023-03-31 20:13:55 +02:00
}
},
2023-03-10 17:52:20 +01:00
}
func init() {
2023-03-31 20:13:55 +02:00
rootCmd.AddCommand(importCmd)
2023-03-10 17:52:20 +01:00
2023-03-31 20:13:55 +02:00
importCmd.Flags().StringP("file", "f", "import.json", "File to use for import operation")
2023-03-10 17:52:20 +01:00
}