File: hosts.go

package info (click to toggle)
golang-github-smallstep-cli 0.15.16%2Bds-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 4,404 kB
  • sloc: sh: 512; makefile: 99
file content (86 lines) | stat: -rw-r--r-- 1,832 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package ssh

import (
	"fmt"
	"os"
	"text/tabwriter"

	"github.com/smallstep/certificates/ca"
	"github.com/smallstep/cli/command"
	"github.com/smallstep/cli/errs"
	"github.com/smallstep/cli/flags"
	"github.com/smallstep/cli/utils/cautils"
	"github.com/urfave/cli"
)

func hostsCommand() cli.Command {
	return cli.Command{
		Name:   "hosts",
		Action: command.ActionFunc(hostsAction),
		Usage:  "returns a list of all valid hosts",
		UsageText: `**step ssh hosts**
[**--set**=<key=value>] [**--set-file**=<path>]
[**--ca-url**=<uri>] [**--root**=<file>]
[**--offline**] [**--ca-config**=<path>]`,
		Description: `**step ssh hosts** returns a list of valid hosts for SSH.

This command returns a zero exit status then the server exists, it will return 1
otherwise.

## EXAMPLES

Get a list of valid hosts for SSH:
'''
$ step ssh hosts
'''`,
		Flags: []cli.Flag{
			flags.TemplateSet,
			flags.TemplateSetFile,
			flags.CaURL,
			flags.Root,
			flags.Offline,
			flags.CaConfig,
		},
	}
}

func hostsAction(ctx *cli.Context) error {
	if err := errs.NumberOfArguments(ctx, 0); err != nil {
		return err
	}

	// Prepare retry function
	retryFunc, err := loginOnUnauthorized(ctx)
	if err != nil {
		return err
	}

	// Initialize CA client with login if needed.
	client, err := cautils.NewClient(ctx, ca.WithRetryFunc(retryFunc))
	if err != nil {
		return err
	}

	resp, err := client.SSHGetHosts()
	if err != nil {
		return err
	}

	w := new(tabwriter.Writer)
	// Format in tab-separated columns with a tab stop of 8.
	w.Init(os.Stdout, 0, 8, 1, '\t', 0)

	fmt.Fprintln(w, "HOSTNAME\tID\tTAGS")
	for _, h := range resp.Hosts {
		tags := ""
		for i, ht := range h.HostTags {
			if i > 0 {
				tags += ","
			}
			tags += ht.Name + "=" + ht.Value
		}
		fmt.Fprintf(w, "%s\t%s\t%s\n", h.Hostname, h.HostID, tags)
	}
	w.Flush()
	return nil
}