feat: add host actions, lifecycle hooks and operational tools
Test / test (push) Successful in 4m4s
Release / release (push) Successful in 7m39s

This commit is contained in:
Sebastian Unterschütz committed 2026-11-18 10:41:36 +01:00
1 parent 8d4915543e
commit e5bde9c61f
32 files changed
+2083 -64

No files matched your search

+164
View File
@@ -0,0 +1,164 @@
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/url"
"os"
"strings"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/setup"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/storage"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
// Portable config deliberately omits arbitrary command/hook/SSH option strings:
// secrets may be embedded there, and cannot reliably be detected by key name.
func portableConfig(c config.Config) map[string]any {
cleanURL := func(raw string) string {
u, err := url.Parse(raw)
if err != nil {
return ""
}
u.User = nil
u.RawQuery = ""
u.Fragment = ""
return u.String()
}
sources := []map[string]any{}
for _, s := range c.NetBoxes {
sources = append(sources, map[string]any{"name": s.Name, "url": cleanURL(s.URL), "disable_prefix": s.DisablePrefix})
}
hosts := []map[string]any{}
for _, h := range c.Hosts {
hosts = append(hosts, map[string]any{"name": h.Name, "address": h.Address, "user": h.User, "port": h.Port, "tags": h.Tags})
}
rewrites := []map[string]string{}
for _, r := range c.Shortcuts.Rewrites {
rewrites = append(rewrites, map[string]string{"pattern": r.Pattern, "replace": r.Replace})
}
out := map[string]any{
"hosts": hosts, "groups": c.Groups,
"ssh": map[string]any{"default_user": c.SSH.DefaultUser, "default_port": c.SSH.DefaultPort},
"resolver": map[string]any{"strategies": c.Resolver.Strategies, "management_subnets": c.Resolver.ManagementSubnets, "interface_name": c.Resolver.InterfaceName, "hostname_domain": c.Resolver.HostnameDomain},
"shortcuts": map[string]any{"domains": c.Shortcuts.Domains, "rewrites": rewrites, "strip_hyphens": c.Shortcuts.StripHyphens, "show": c.Shortcuts.Show},
"completion": map[string]any{"max_results": c.Completion.MaxResults},
"tui": map[string]any{"history_limit": c.TUI.HistoryLimit},
}
if len(sources) > 0 {
out["netboxes"] = sources
} else if c.NetBox.URL != "" {
out["netbox"] = map[string]string{"url": cleanURL(c.NetBox.URL)}
}
return out
}
func decodePortable(data []byte) (config.Config, error) {
v := viper.New()
v.SetConfigType("yaml")
v.SetDefault("tui.history_limit", 10)
var c config.Config
if err := v.ReadConfig(bytes.NewReader(data)); err != nil {
return c, err
}
if err := v.Unmarshal(&c); err != nil {
return c, err
}
// Strip executable settings and credentials even from externally edited files.
safe, _ := json.Marshal(portableConfig(c))
v = viper.New()
v.SetConfigType("json")
if err := v.ReadConfig(bytes.NewReader(safe)); err != nil {
return c, err
}
c = config.Config{}
err := v.Unmarshal(&c)
return c, err
}
func configCmd() *cobra.Command {
cmd := &cobra.Command{Use: "config", Short: "Share configuration without credentials or executable settings"}
export := &cobra.Command{Use: "export [FILE]", Short: "Export a secret-free JSON configuration (also valid YAML)", Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
data, err := json.MarshalIndent(portableConfig(*cfg), "", " ")
if err != nil {
return err
}
if len(args) == 0 {
fmt.Fprintln(cmd.OutOrStdout(), string(data))
return nil
}
return storage.WriteFile(args[0], append(data, '\n'), 0600)
}}
var yes, dry bool
imp := &cobra.Command{Use: "import FILE", Short: "Import shared host settings; preserve matching local credentials and commands", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error {
data, err := os.ReadFile(args[0])
if err != nil {
return err
}
incoming, err := decodePortable(data)
if err != nil {
return err
}
current, err := config.Load()
if err != nil {
return err
}
same := func(a, b string) bool { return strings.TrimRight(a, "/") == strings.TrimRight(b, "/") }
for i := range incoming.NetBoxes {
for _, old := range current.NetBoxes {
s := &incoming.NetBoxes[i]
if strings.EqualFold(s.Name, old.Name) && same(s.URL, old.URL) {
s.Token = old.Token
s.TokenVersion = old.TokenVersion
s.SSH = old.SSH
}
}
}
if incoming.NetBox.URL != "" && same(incoming.NetBox.URL, current.NetBox.URL) {
incoming.NetBox.Token = current.NetBox.Token
incoming.NetBox.TokenVersion = current.NetBox.TokenVersion
incoming.NetBox.SSH = current.NetBox.SSH
}
incoming.Commands = current.Commands
incoming.Activity = current.Activity
incoming.Cache = current.Cache
incoming.Multi = current.Multi
incoming.Shell = current.Shell
incoming.SSH.SSHOptions = current.SSH.SSHOptions
incoming.SSH.Rules = current.SSH.Rules
for i := range incoming.Hosts {
for _, old := range current.Hosts {
if incoming.Hosts[i].Name == old.Name && incoming.Hosts[i].Address == old.Address {
incoming.Hosts[i].SSH = old.SSH
}
}
}
for _, validate := range []func() error{incoming.ValidateNetBoxes, incoming.ValidateHosts, incoming.ValidateSSH, incoming.ValidateCommands, incoming.ValidateOperations, incoming.Shortcuts.Validate, incoming.ValidateMulti} {
if err := validate(); err != nil {
return err
}
}
fmt.Fprintf(cmd.OutOrStdout(), "Import: %d named instances, %d static hosts. Local commands and matching credentials are retained.\n", len(incoming.NetBoxes), len(incoming.Hosts))
if dry {
return nil
}
if err := confirmAction("Replace shared configuration settings", yes); err != nil {
return err
}
if existing, err := os.ReadFile(config.Path()); err == nil {
if err := storage.WriteFile(config.Path()+".before-import", existing, 0600); err != nil {
return err
}
}
return setup.Save(incoming)
}}
imp.Flags().BoolVar(&yes, "yes", false, "Approve replacing shared configuration settings")
imp.Flags().BoolVar(&dry, "dry-run", false, "Validate and preview without writing")
cmd.AddCommand(export, imp)
return cmd
}