ipam/cmd/export.go

97 lines
2.2 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 (
"encoding/json"
"fmt"
"net/netip"
"os"
"path"
"time"
2023-03-10 17:52:20 +01:00
"github.com/spf13/cobra"
2023-03-10 17:52:20 +01:00
)
// exportCmd represents the export command
var exportCmd = &cobra.Command{
Use: "export",
Short: "Export ipam configuration",
Long: `Export current ipam contents to importable data format.
2023-03-24 16:27:45 +01:00
You can either export a single subnet or all subnets.`,
Example: "ipam export\nipam export 192.168.0.0/24",
Args: cobra.RangeArgs(0, 1),
Aliases: []string{"ex"},
Run: func(cmd *cobra.Command, args []string) {
var jsonoutput []Subnet
if len(args) == 1 {
prefix, parseerr := netip.ParsePrefix(args[0])
if parseerr != nil {
fmt.Println("[ERROR]", parseerr)
os.Exit(1)
}
2023-03-24 16:27:45 +01:00
subnet, geterr := GetSubnet(prefix)
if geterr != nil {
fmt.Println("[ERROR]", geterr)
os.Exit(1)
}
jsonoutput = append(jsonoutput, subnet)
} else {
subnetlist := ListSubnets()
for _, net := range subnetlist {
prefix, parseerr := netip.ParsePrefix(net)
if parseerr != nil {
fmt.Println("[ERROR]", parseerr)
os.Exit(1)
}
subnet, geterr := GetSubnet(prefix)
if geterr != nil {
fmt.Println("[ERROR]", geterr)
os.Exit(1)
}
jsonoutput = append(jsonoutput, subnet)
}
}
2023-03-24 16:27:45 +01:00
//workingdir, _ := os.Getwd()
//timestamp := time.Now().Format("2006-01-02_15-04")
//exportfilename := workingdir + "/ipam_export_" + timestamp + ".json"
2023-03-24 16:27:45 +01:00
var exportname string
2023-03-24 16:27:45 +01:00
flagpath, _ := cmd.Flags().GetString("file")
if path.IsAbs(flagpath) {
exportname = flagpath
} else {
wd, _ := os.Getwd()
exportname = path.Join(wd, flagpath)
}
2023-03-24 16:27:45 +01:00
data, _ := json.MarshalIndent(jsonoutput, "", " ")
2023-03-24 16:27:45 +01:00
file, fileerr := os.Create(exportname)
if fileerr != nil {
fmt.Println("[ERROR]", fileerr)
os.Exit(1)
}
defer file.Close()
2023-03-24 16:27:45 +01:00
_, writeerr := file.Write(data)
if writeerr != nil {
fmt.Println("[ERROR]", writeerr)
os.Exit(1)
}
fmt.Printf("[INFO] Data was exported to file %v\n", exportname)
},
2023-03-10 17:52:20 +01:00
}
func init() {
rootCmd.AddCommand(exportCmd)
2023-03-10 17:52:20 +01:00
timestamp := time.Now().Format("2006-01-02_15-04")
exportCmd.Flags().StringP("file", "f", "./ipam_export_"+timestamp+".json", "File name for exported data.\nCan be both absolute or relative path.")
2023-03-10 17:52:20 +01:00
}