1
0
mirror of https://github.com/smallstep/cli.git synced 2026-10-25 23:19:18 +03:00
Files
step-ca-cli/command/ssh/hosts.go
Max 11602a26fd Merge pull request #229 from smallstep/seb/ssh-hosts-formatting
Cosmetic improvement: avoid unintentional concat of columns
2020-04-09 15:23:24 -07:00

84 lines
1.7 KiB
Go

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**
[**--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.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.Fprintln(w, fmt.Sprintf("%s\t%s\t%s", h.Hostname, h.HostID, tags))
}
w.Flush()
return nil
}