feat: NetBox insights, host tools and configurable TUI
Test / test (pull_request) Successful in 4m15s
Test / test (pull_request) Successful in 4m15s
- info/open/whois: NetBox details (site, nested locations, rack units, role, platform, tenant, IPs per interface), web page, reverse IP lookup - cache status, site, role, platform, tenant, location chain and rack; ask before connecting to hosts in ssh.warn_status (--force skips) - ssh rules and command restrictions match site/role/platform/tenant/status - tui.columns selects what the TUI shows; optional TCP reachability column; detail view (Ctrl+L), NetBox page (Ctrl+G), status/location filters - resolver.fallback tries other strategies' addresses when unreachable - copy-id, known-hosts reset and address-change notices - export ansible (YAML/INI) and export ssh-config - token: keyring stores NetBox tokens in the system keyring - fix stale menu number in testenv configure test Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e5bde9c61f
commit
1660bb3098
39 files changed
+4868
-96
No files matched your search
@@ -71,10 +71,15 @@ func editCommands(cfg *config.Config) error {
|
||||
huh.NewInput().Title("Only for instance").Value(&command.Match.Instance),
|
||||
huh.NewInput().Title("Only for kind").Description("device, vm or static; empty means all.").Value(&command.Match.Kind),
|
||||
huh.NewInput().Title("Only for hostname pattern").Description("For example router*; all specified filters must match.").Value(&command.Match.Name),
|
||||
huh.NewInput().Title("Only for site").Description("NetBox site name or slug.").Value(&command.Match.Site),
|
||||
huh.NewInput().Title("Only for role").Description("NetBox device/VM role name or slug.").Value(&command.Match.Role),
|
||||
huh.NewInput().Title("Only for platform").Description("NetBox platform name or slug, e.g. junos.").Value(&command.Match.Platform),
|
||||
huh.NewInput().Title("Only for status").Description("NetBox status value, e.g. active.").Value(&command.Match.Status),
|
||||
).Title("Local command")).Run()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
command.Match = trimMatch(command.Match)
|
||||
command.Args = []string{binary}
|
||||
if arguments != "" {
|
||||
command.Args = append(command.Args, strings.Split(arguments, "\n")...)
|
||||
|
||||
@@ -11,6 +11,12 @@ import (
|
||||
func editOperations(cfg *config.Config) error {
|
||||
history, days, entries := strconv.Itoa(cfg.TUI.HistoryLimit), strconv.Itoa(cfg.Activity.RetentionDays), strconv.Itoa(cfg.Activity.MaxEntries)
|
||||
enabled := cfg.Activity.Enabled
|
||||
columns := append([]string(nil), cfg.TUI.EffectiveColumns()...)
|
||||
timeout := strconv.Itoa(int(cfg.TUI.ReachabilityTimeoutDuration().Milliseconds()))
|
||||
columnOptions := make([]huh.Option[string], 0, len(config.TUIColumns))
|
||||
for _, column := range config.TUIColumns {
|
||||
columnOptions = append(columnOptions, huh.NewOption(columnLabels[column], column).Selected(contains(columns, column)))
|
||||
}
|
||||
valid := func(s string) error {
|
||||
n, err := strconv.Atoi(s)
|
||||
if err != nil || n < 0 {
|
||||
@@ -23,13 +29,56 @@ func editOperations(cfg *config.Config) error {
|
||||
huh.NewConfirm().Title("Record local action history?").Description("Stores host, command name, duration and exit code; no arguments or output.").Value(&enabled),
|
||||
huh.NewInput().Title("Retention in days").Description("0 = no age limit").Value(&days).Validate(valid),
|
||||
huh.NewInput().Title("Maximum recorded actions").Description("0 = no count limit").Value(&entries).Validate(valid),
|
||||
).Title("History & activity")).Run()
|
||||
).Title("History & activity"), huh.NewGroup(
|
||||
huh.NewMultiSelect[string]().Title("Shown in the TUI next to each host").
|
||||
Description("Reachability opens a TCP connection to every listed host's SSH port.").
|
||||
Options(columnOptions...).Value(&columns),
|
||||
huh.NewInput().Title("Reachability timeout (ms)").Description("300 by default").Value(&timeout).Validate(valid),
|
||||
).Title("TUI display")).Run()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cfg.TUI.Columns = orderColumns(cfg.TUI.EffectiveColumns(), columns)
|
||||
if ms, _ := strconv.Atoi(timeout); ms != 300 {
|
||||
cfg.TUI.ReachabilityTimeout = ms
|
||||
} else {
|
||||
cfg.TUI.ReachabilityTimeout = 0
|
||||
}
|
||||
cfg.TUI.HistoryLimit, _ = strconv.Atoi(history)
|
||||
cfg.Activity.RetentionDays, _ = strconv.Atoi(days)
|
||||
cfg.Activity.MaxEntries, _ = strconv.Atoi(entries)
|
||||
cfg.Activity.Enabled = enabled
|
||||
return nil
|
||||
}
|
||||
|
||||
var columnLabels = map[string]string{
|
||||
"alias": "Shortcut alias", "ip": "IP address", "kind": "Kind (device/vm/static)", "source": "Source (live/cache/static)",
|
||||
"status": "NetBox status (if not active)", "site": "Site", "location": "Location (site › locations › rack › U)", "role": "Role", "platform": "Platform", "tenant": "Tenant",
|
||||
"cluster": "Cluster", "tags": "Tags", "reachability": "Reachability (TCP check ✓/✗)",
|
||||
}
|
||||
|
||||
func contains(list []string, value string) bool {
|
||||
for _, item := range list {
|
||||
if item == value {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// orderColumns keeps an existing custom order and appends new selections in
|
||||
// the canonical order; the multi-select itself does not preserve order.
|
||||
func orderColumns(previous, selected []string) []string {
|
||||
out := []string{}
|
||||
for _, column := range previous {
|
||||
if contains(selected, column) {
|
||||
out = append(out, column)
|
||||
}
|
||||
}
|
||||
for _, column := range config.TUIColumns {
|
||||
if contains(selected, column) && !contains(out, column) {
|
||||
out = append(out, column)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
+28
-6
@@ -262,22 +262,36 @@ func editRule(rule config.SSHRule, sources []config.NetBoxConfig) (config.SSHRul
|
||||
Title("Kind").
|
||||
Options(huh.NewOption("(any)", ""), huh.NewOption("device", "device"), huh.NewOption("vm", "vm")).
|
||||
Value(&match.Kind),
|
||||
huh.NewInput().
|
||||
Title("Site").
|
||||
Description("NetBox site name or slug, e.g. fsn1").
|
||||
Value(&match.Site),
|
||||
huh.NewInput().
|
||||
Title("Role").
|
||||
Description("NetBox device/VM role name or slug, e.g. core-switch").
|
||||
Value(&match.Role),
|
||||
huh.NewInput().
|
||||
Title("Platform").
|
||||
Description("NetBox platform name or slug, e.g. junos").
|
||||
Value(&match.Platform),
|
||||
huh.NewInput().
|
||||
Title("Status").
|
||||
Description("NetBox status value, e.g. active").
|
||||
Value(&match.Status),
|
||||
huh.NewInput().
|
||||
Title("Name pattern").
|
||||
Description("Shell-style glob without instance prefix, e.g. *.dmz.example.com").
|
||||
Value(&match.Name).
|
||||
Validate(func(s string) error {
|
||||
candidate := match
|
||||
candidate.Tag = strings.TrimSpace(candidate.Tag)
|
||||
candidate.Name = strings.TrimSpace(s)
|
||||
return candidate.Validate("rule")
|
||||
candidate.Name = s
|
||||
return trimMatch(candidate).Validate("rule")
|
||||
}),
|
||||
).Title("Rule match")).Run()
|
||||
if err != nil {
|
||||
return rule, err
|
||||
}
|
||||
match.Tag = strings.TrimSpace(match.Tag)
|
||||
match.Name = strings.TrimSpace(match.Name)
|
||||
match = trimMatch(match)
|
||||
|
||||
options, err := editSSHOptions("SSH options for rule "+describeMatch(match), rule.SSHOptions)
|
||||
if err != nil {
|
||||
@@ -288,10 +302,18 @@ func editRule(rule config.SSHRule, sources []config.NetBoxConfig) (config.SSHRul
|
||||
|
||||
func describeMatch(m config.SSHMatch) string {
|
||||
var parts []string
|
||||
for _, field := range [][2]string{{"tag", m.Tag}, {"instance", m.Instance}, {"kind", m.Kind}, {"name", m.Name}} {
|
||||
for _, field := range matchFields(m) {
|
||||
if field[1] != "" {
|
||||
parts = append(parts, field[0]+"="+field[1])
|
||||
}
|
||||
}
|
||||
return "[" + strings.Join(parts, " ") + "]"
|
||||
}
|
||||
|
||||
// trimMatch removes surrounding spaces from every selector.
|
||||
func trimMatch(m config.SSHMatch) config.SSHMatch {
|
||||
for _, field := range []*string{&m.Tag, &m.Instance, &m.Kind, &m.Name, &m.Site, &m.Role, &m.Platform, &m.Tenant, &m.Status} {
|
||||
*field = strings.TrimSpace(*field)
|
||||
}
|
||||
return m
|
||||
}
|
||||
@@ -426,6 +426,12 @@ func save(cfg config.Config) error {
|
||||
for _, s := range cfg.Resolver.Strategies {
|
||||
fmt.Fprintf(&b, " - %s\n", s)
|
||||
}
|
||||
if cfg.Resolver.Fallback {
|
||||
b.WriteString(" fallback: true\n")
|
||||
}
|
||||
if cfg.Resolver.FallbackTimeout > 0 {
|
||||
fmt.Fprintf(&b, " fallback_timeout: %d\n", cfg.Resolver.FallbackTimeout)
|
||||
}
|
||||
if len(cfg.Resolver.ManagementSubnets) > 0 {
|
||||
b.WriteString(" management_subnets:\n")
|
||||
for _, s := range cfg.Resolver.ManagementSubnets {
|
||||
@@ -452,12 +458,19 @@ func save(cfg config.Config) error {
|
||||
if cfg.SSH.DefaultPort > 0 {
|
||||
fmt.Fprintf(&b, " default_port: %d\n", cfg.SSH.DefaultPort)
|
||||
}
|
||||
if cfg.SSH.WarnStatus != nil && !sameStrings(cfg.SSH.WarnStatus, config.DefaultWarnStatus) {
|
||||
quoted := make([]string, 0, len(cfg.SSH.WarnStatus))
|
||||
for _, status := range cfg.SSH.WarnStatus {
|
||||
quoted = append(quoted, strconv.Quote(status))
|
||||
}
|
||||
fmt.Fprintf(&b, " warn_status: [%s]\n", strings.Join(quoted, ", "))
|
||||
}
|
||||
writeSSHOptions(&b, " ", cfg.SSH.SSHOptions)
|
||||
if len(cfg.SSH.Rules) > 0 {
|
||||
b.WriteString(" rules:\n")
|
||||
for _, rule := range cfg.SSH.Rules {
|
||||
b.WriteString(" - match:\n")
|
||||
for _, field := range [][2]string{{"tag", rule.Match.Tag}, {"instance", rule.Match.Instance}, {"kind", rule.Match.Kind}, {"name", rule.Match.Name}} {
|
||||
for _, field := range matchFields(rule.Match) {
|
||||
if field[1] != "" {
|
||||
fmt.Fprintf(&b, " %s: %q\n", field[0], field[1])
|
||||
}
|
||||
@@ -561,7 +574,7 @@ func save(cfg config.Config) error {
|
||||
fmt.Fprintf(&b, " confirm: %t\n timeout: %q\n post_run: %q\n", command.Confirm, command.Timeout, command.PostRun)
|
||||
if command.Match != (config.SSHMatch{}) {
|
||||
b.WriteString(" match:\n")
|
||||
for _, pair := range [][2]string{{"tag", command.Match.Tag}, {"instance", command.Match.Instance}, {"kind", command.Match.Kind}, {"name", command.Match.Name}} {
|
||||
for _, pair := range matchFields(command.Match) {
|
||||
if pair[1] != "" {
|
||||
fmt.Fprintf(&b, " %s: %q\n", pair[0], pair[1])
|
||||
}
|
||||
@@ -570,7 +583,14 @@ func save(cfg config.Config) error {
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Fprintf(&b, "\ntui:\n history_limit: %d\nactivity:\n enabled: %t\n retention_days: %d\n max_entries: %d\n", cfg.TUI.HistoryLimit, cfg.Activity.Enabled, cfg.Activity.RetentionDays, cfg.Activity.MaxEntries)
|
||||
fmt.Fprintf(&b, "\ntui:\n history_limit: %d\n", cfg.TUI.HistoryLimit)
|
||||
if cfg.TUI.Columns != nil && !sameStrings(cfg.TUI.Columns, config.DefaultTUIColumns) {
|
||||
fmt.Fprintf(&b, " columns: [%s]\n", strings.Join(cfg.TUI.Columns, ", "))
|
||||
}
|
||||
if cfg.TUI.ReachabilityTimeout > 0 {
|
||||
fmt.Fprintf(&b, " reachability_timeout: %d\n", cfg.TUI.ReachabilityTimeout)
|
||||
}
|
||||
fmt.Fprintf(&b, "activity:\n enabled: %t\n retention_days: %d\n max_entries: %d\n", cfg.Activity.Enabled, cfg.Activity.RetentionDays, cfg.Activity.MaxEntries)
|
||||
if cfg.Shell.Alias != "" {
|
||||
fmt.Fprintf(&b, "\nshell:\n alias: %q\n", cfg.Shell.Alias)
|
||||
}
|
||||
@@ -628,3 +648,21 @@ func writeSSHOptions(b *strings.Builder, indent string, o config.SSHOptions) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// matchFields lists the selectors of a rule or command match in config order.
|
||||
func matchFields(m config.SSHMatch) [][2]string {
|
||||
return [][2]string{{"tag", m.Tag}, {"instance", m.Instance}, {"kind", m.Kind}, {"name", m.Name},
|
||||
{"site", m.Site}, {"role", m.Role}, {"platform", m.Platform}, {"tenant", m.Tenant}, {"status", m.Status}}
|
||||
}
|
||||
|
||||
func sameStrings(a, b []string) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
for i := range a {
|
||||
if !strings.EqualFold(a[i], b[i]) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -715,7 +715,59 @@ func TestOperationsRoundTrip(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.TUI != cfg.TUI || got.Activity != cfg.Activity || !reflect.DeepEqual(got.Commands, cfg.Commands) || !reflect.DeepEqual(got.SSH, cfg.SSH) {
|
||||
if !reflect.DeepEqual(got.TUI, cfg.TUI) || got.Activity != cfg.Activity || !reflect.DeepEqual(got.Commands, cfg.Commands) || !reflect.DeepEqual(got.SSH, cfg.SSH) {
|
||||
t.Fatalf("round trip lost operations: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveRoundtripNetBoxInsightSettings(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Setenv("XDG_CONFIG_HOME", dir)
|
||||
cfg := config.Config{
|
||||
NetBox: config.NetBoxConfig{URL: "https://nb.example", Token: "keyring"},
|
||||
Resolver: config.ResolverConfig{Strategies: []string{"primary_ip"}, Fallback: true, FallbackTimeout: 400},
|
||||
TUI: config.TUIConfig{HistoryLimit: 10, Columns: []string{"ip", "platform", "reachability"}, ReachabilityTimeout: 900},
|
||||
SSH: config.SSHConfig{WarnStatus: []string{"planned"}, Rules: []config.SSHRule{{
|
||||
Match: config.SSHMatch{Platform: "junos", Site: "fsn1", Role: "core", Tenant: "acme", Status: "active"},
|
||||
SSHOptions: config.SSHOptions{ProxyJump: "jump"},
|
||||
}}},
|
||||
Commands: map[string]config.HostCommand{"cli": {Args: []string{"cli", "{address}"}, Match: config.SSHMatch{Platform: "eos"}}},
|
||||
}
|
||||
if err := Save(cfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
loaded, err := config.Load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !loaded.Resolver.Fallback || loaded.Resolver.FallbackTimeout != 400 {
|
||||
t.Fatalf("resolver lost: %+v", loaded.Resolver)
|
||||
}
|
||||
if !reflect.DeepEqual(loaded.TUI.Columns, []string{"ip", "platform", "reachability"}) || !loaded.TUI.ReachabilityEnabled() || loaded.TUI.ReachabilityTimeout != 900 {
|
||||
t.Fatalf("tui lost: %+v", loaded.TUI)
|
||||
}
|
||||
if !loaded.SSH.WarnsStatus("planned") || loaded.SSH.WarnsStatus("offline") {
|
||||
t.Fatalf("warn_status lost: %v", loaded.SSH.WarnStatus)
|
||||
}
|
||||
if got := loaded.SSH.Rules[0].Match; got != cfg.SSH.Rules[0].Match {
|
||||
t.Fatalf("rule match lost: %+v", got)
|
||||
}
|
||||
if loaded.Commands["cli"].Match.Platform != "eos" {
|
||||
t.Fatalf("command match lost: %+v", loaded.Commands["cli"].Match)
|
||||
}
|
||||
if !config.IsKeyringToken(loaded.NetBox.Token) || loaded.NetBox.TokenVersion != 0 {
|
||||
t.Fatalf("keyring token changed: %+v", loaded.NetBox)
|
||||
}
|
||||
|
||||
// Defaults stay implicit, so later default changes reach existing configs.
|
||||
cfg = config.Config{NetBox: config.NetBoxConfig{URL: "https://nb.example"}, Resolver: config.ResolverConfig{Strategies: []string{"primary_ip"}}}
|
||||
if err := Save(cfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data, _ := os.ReadFile(filepath.Join(dir, "netssh.yaml"))
|
||||
for _, key := range []string{"warn_status", "columns", "reachability", "fallback"} {
|
||||
if strings.Contains(string(data), key) {
|
||||
t.Errorf("default %s written:\n%s", key, data)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user