github.com/anth0d/nomad@v0.0.0-20221214183521-ae3a0a2cad06/command/acl_token_list.go (about) 1 package command 2 3 import ( 4 "fmt" 5 "strings" 6 "time" 7 8 "github.com/hashicorp/nomad/api" 9 "github.com/posener/complete" 10 ) 11 12 type ACLTokenListCommand struct { 13 Meta 14 } 15 16 func (c *ACLTokenListCommand) Help() string { 17 helpText := ` 18 Usage: nomad acl token list 19 20 List is used to list existing ACL tokens. 21 22 General Options: 23 24 ` + generalOptionsUsage(usageOptsDefault|usageOptsNoNamespace) + ` 25 26 List Options: 27 28 -json 29 Output the ACL tokens in a JSON format. 30 31 -t 32 Format and display the ACL tokens using a Go template. 33 ` 34 35 return strings.TrimSpace(helpText) 36 } 37 38 func (c *ACLTokenListCommand) AutocompleteFlags() complete.Flags { 39 return mergeAutocompleteFlags(c.Meta.AutocompleteFlags(FlagSetClient), 40 complete.Flags{ 41 "-json": complete.PredictNothing, 42 "-t": complete.PredictAnything, 43 }) 44 } 45 46 func (c *ACLTokenListCommand) AutocompleteArgs() complete.Predictor { 47 return complete.PredictNothing 48 } 49 50 func (c *ACLTokenListCommand) Synopsis() string { 51 return "List ACL tokens" 52 } 53 54 func (c *ACLTokenListCommand) Name() string { return "acl token list" } 55 56 func (c *ACLTokenListCommand) Run(args []string) int { 57 var json bool 58 var tmpl string 59 60 flags := c.Meta.FlagSet(c.Name(), FlagSetClient) 61 flags.Usage = func() { c.Ui.Output(c.Help()) } 62 flags.BoolVar(&json, "json", false, "") 63 flags.StringVar(&tmpl, "t", "", "") 64 65 if err := flags.Parse(args); err != nil { 66 return 1 67 } 68 69 // Check that we got no arguments 70 args = flags.Args() 71 if l := len(args); l != 0 { 72 c.Ui.Error("This command takes no arguments") 73 c.Ui.Error(commandErrorText(c)) 74 return 1 75 } 76 77 // Get the HTTP client 78 client, err := c.Meta.Client() 79 if err != nil { 80 c.Ui.Error(fmt.Sprintf("Error initializing client: %s", err)) 81 return 1 82 } 83 84 // Fetch info on the policy 85 tokens, _, err := client.ACLTokens().List(nil) 86 if err != nil { 87 c.Ui.Error(fmt.Sprintf("Error listing ACL tokens: %s", err)) 88 return 1 89 } 90 91 if json || len(tmpl) > 0 { 92 out, err := Format(json, tmpl, tokens) 93 if err != nil { 94 c.Ui.Error(err.Error()) 95 return 1 96 } 97 98 c.Ui.Output(out) 99 return 0 100 } 101 102 c.Ui.Output(formatTokens(tokens)) 103 return 0 104 } 105 106 func formatTokens(tokens []*api.ACLTokenListStub) string { 107 if len(tokens) == 0 { 108 return "No tokens found" 109 } 110 111 output := make([]string, 0, len(tokens)+1) 112 output = append(output, "Name|Type|Global|Accessor ID|Expired") 113 for _, p := range tokens { 114 expired := false 115 if p.ExpirationTime != nil && !p.ExpirationTime.IsZero() { 116 if p.ExpirationTime.Before(time.Now().UTC()) { 117 expired = true 118 } 119 } 120 121 output = append(output, fmt.Sprintf( 122 "%s|%s|%t|%s|%v", p.Name, p.Type, p.Global, p.AccessorID, expired)) 123 } 124 125 return formatList(output) 126 }