Debian Codegraph @

command/ssh/hosts.go

raw symbols SCIP
1 package ssh
2
3 import (
4 "fmt"
5 "os"
6 "text/tabwriter"
7
8 "github.com/smallstep/certificates/ca"
9 "github.com/smallstep/cli/command"
10 "github.com/smallstep/cli/errs"
11 "github.com/smallstep/cli/flags"
12 "github.com/smallstep/cli/utils/cautils"
13 "github.com/urfave/cli"
14 )
15
16 func hostsCommand() cli.Command {
17 return cli.Command{
18 Name: "hosts",
19 Action: command.ActionFunc(hostsAction),
20 Usage: "returns a list of all valid hosts",
21 UsageText: `**step ssh hosts**
22 [**--set**=<key=value>] [**--set-file**=<path>]
23 [**--ca-url**=<uri>] [**--root**=<file>]
24 [**--offline**] [**--ca-config**=<path>]`,
25 Description: `**step ssh hosts** returns a list of valid hosts for SSH.
26
27 This command returns a zero exit status then the server exists, it will return 1
28 otherwise.
29
30 ## EXAMPLES
31
32 Get a list of valid hosts for SSH:
33 '''
34 $ step ssh hosts
35 '''`,
36 Flags: []cli.Flag{
37 flags.TemplateSet,
38 flags.TemplateSetFile,
39 flags.CaURL,
40 flags.Root,
41 flags.Offline,
42 flags.CaConfig,
43 },
44 }
45 }
46
47 func hostsAction(ctx *cli.Context) error {
48 if err := errs.NumberOfArguments(ctx, 0); err != nil {
49 return err
50 }
51
52 // Prepare retry function
53 retryFunc, err := loginOnUnauthorized(ctx)
54 if err != nil {
55 return err
56 }
57
58 // Initialize CA client with login if needed.
59 client, err := cautils.NewClient(ctx, ca.WithRetryFunc(retryFunc))
60 if err != nil {
61 return err
62 }
63
64 resp, err := client.SSHGetHosts()
65 if err != nil {
66 return err
67 }
68
69 w := new(tabwriter.Writer)
70 // Format in tab-separated columns with a tab stop of 8.
71 w.Init(os.Stdout, 0, 8, 1, '\t', 0)
72
73 fmt.Fprintln(w, "HOSTNAME\tID\tTAGS")
74 for _, h := range resp.Hosts {
75 tags := ""
76 for i, ht := range h.HostTags {
77 if i > 0 {
78 tags += ","
79 }
80 tags += ht.Name + "=" + ht.Value
81 }
82 fmt.Fprintf(w, "%s\t%s\t%s\n", h.Hostname, h.HostID, tags)
83 }
84 w.Flush()
85 return nil
86 }