1package command
2
3import (
4	"fmt"
5	"strings"
6
7	"github.com/posener/complete"
8)
9
10type SentinelReadCommand struct {
11	Meta
12}
13
14func (c *SentinelReadCommand) Help() string {
15	helpText := `
16Usage: nomad sentinel read [options] <name>
17
18  Read is used to inspect a Sentinel policy.
19
20General Options:
21
22  ` + generalOptionsUsage() + `
23
24Read Options:
25
26  -raw
27    Prints only the raw policy
28
29`
30	return strings.TrimSpace(helpText)
31}
32
33func (c *SentinelReadCommand) AutocompleteFlags() complete.Flags {
34	return mergeAutocompleteFlags(c.Meta.AutocompleteFlags(FlagSetClient),
35		complete.Flags{
36			"-raw": complete.PredictNothing,
37		})
38}
39
40func (c *SentinelReadCommand) AutocompleteArgs() complete.Predictor {
41	return complete.PredictNothing
42}
43
44func (c *SentinelReadCommand) Synopsis() string {
45	return "Inspects an existing Sentinel policies"
46}
47
48func (c *SentinelReadCommand) Name() string { return "sentinel read" }
49
50func (c *SentinelReadCommand) Run(args []string) int {
51	var raw bool
52	flags := c.Meta.FlagSet(c.Name(), FlagSetClient)
53	flags.Usage = func() { c.Ui.Output(c.Help()) }
54	flags.BoolVar(&raw, "raw", false, "")
55	if err := flags.Parse(args); err != nil {
56		return 1
57	}
58
59	// Check that we got exactly one arguments
60	args = flags.Args()
61	if l := len(args); l != 1 {
62		c.Ui.Error("This command takes one argument: <name>")
63		c.Ui.Error(commandErrorText(c))
64		return 1
65	}
66
67	// Get the name and file
68	policyName := args[0]
69
70	// Get the HTTP client
71	client, err := c.Meta.Client()
72	if err != nil {
73		c.Ui.Error(fmt.Sprintf("Error initializing client: %s", err))
74		return 1
75	}
76
77	// Query the policy
78	policy, _, err := client.SentinelPolicies().Info(policyName, nil)
79	if err != nil {
80		c.Ui.Error(fmt.Sprintf("Error querying Sentinel policy: %s", err))
81		return 1
82	}
83
84	// Check for only the raw policy
85	if raw {
86		c.Ui.Output(policy.Policy)
87		return 0
88	}
89
90	// Output the base information
91	info := []string{
92		fmt.Sprintf("Name|%s", policy.Name),
93		fmt.Sprintf("Scope|%s", policy.Scope),
94		fmt.Sprintf("Enforcement Level|%s", policy.EnforcementLevel),
95		fmt.Sprintf("Description|%s", policy.Description),
96	}
97	c.Ui.Output(formatKV(info))
98	c.Ui.Output("Policy:")
99	c.Ui.Output(policy.Policy)
100	return 0
101}
102