Files
ssh-netbox-wrapper/cmd/netssh/run.go
T
Sebastian Unterschütz e5bde9c61f
Test / test (push) Successful in 4m4s
Release / release (push) Successful in 7m39s
feat: add host actions, lifecycle hooks and operational tools
2026-11-18 10:41:36 +01:00

107 lines
3.3 KiB
Go

package main
import (
"fmt"
"os"
"sort"
"strings"
"time"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
"github.com/charmbracelet/x/term"
"github.com/spf13/cobra"
)
// expandHostCommand substitutes each argument once, without shell evaluation.
func expandHostCommand(command config.HostCommand, host resolvedHost, extra []string) []string {
_, name := netbox.SplitTarget(host.Name)
replace := strings.NewReplacer("{host}", name, "{address}", host.IP, "{target}", host.Name)
argv := make([]string, 0, len(command.Args)+len(extra))
for _, arg := range command.Args {
argv = append(argv, replace.Replace(arg))
}
return append(argv, extra...)
}
func runCmd() *cobra.Command {
var dryRun, yes, status bool
cmd := &cobra.Command{
Use: "run [--dry-run] COMMAND HOST [-- EXTRA_ARGS...]",
Short: "Run a configured local command for a NetBox or static host",
Args: cobra.MinimumNArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
command, ok := cfg.Commands[args[0]]
if !ok {
return fmt.Errorf("unknown configured command %q", args[0])
}
host, err := resolveTargetE(cfg, args[1], !dryRun)
if err != nil {
return err
}
if !command.Allowed(commandHost(host)) {
return fmt.Errorf("command %q is not allowed for %s", args[0], host.Name)
}
argv := expandHostCommand(command, host, args[2:])
if dryRun {
if post := config.HookCommand(command.PostRun); post != "" {
fmt.Fprintf(cmd.ErrOrStderr(), "# post_run (skipped in --dry-run): %s\n", post)
}
for i, arg := range argv {
if i > 0 {
fmt.Fprint(cmd.OutOrStdout(), " ")
}
fmt.Fprintf(cmd.OutOrStdout(), "%q", arg)
}
fmt.Fprintln(cmd.OutOrStdout())
return nil
}
if command.Confirm {
if err := confirmAction("Run "+args[0]+" on "+host.Name, yes); err != nil {
return err
}
}
timeout, _ := time.ParseDuration(command.Timeout)
code := supervise(cfg, host, args[0], argv, command.PostRun, timeout, status || term.IsTerminal(os.Stderr.Fd()), os.Stdin, cmd.OutOrStdout(), cmd.ErrOrStderr())
if code != 0 {
cmd.SilenceErrors = true
cmd.SilenceUsage = true
return &commandExit{code}
}
return nil
},
ValidArgsFunction: func(cmd *cobra.Command, args []string, prefix string) ([]string, cobra.ShellCompDirective) {
if len(args) == 0 {
cfg, err := config.Load()
if err != nil {
return nil, cobra.ShellCompDirectiveError
}
var names []string
for name := range cfg.Commands {
if strings.HasPrefix(name, prefix) {
names = append(names, name)
}
}
sort.Strings(names)
return names, cobra.ShellCompDirectiveNoFileComp
}
if len(args) == 1 {
return completeHosts(prefix), cobra.ShellCompDirectiveNoFileComp
}
return nil, cobra.ShellCompDirectiveNoFileComp
},
}
cmd.Flags().BoolVar(&yes, "yes", false, "Approve an action requiring confirmation")
cmd.Flags().BoolVar(&status, "status", false, "Show elapsed runtime")
cmd.Flags().BoolVar(&dryRun, "dry-run", false, "Print the command without running it")
return cmd
}
type commandExit struct{ code int }
func (e *commandExit) Error() string { return fmt.Sprintf("command exited with status %d", e.code) }