1package command 2 3import ( 4 "fmt" 5 "strings" 6 7 "github.com/mitchellh/cli" 8 "github.com/posener/complete" 9) 10 11var ( 12 _ cli.Command = (*PolicyReadCommand)(nil) 13 _ cli.CommandAutocomplete = (*PolicyReadCommand)(nil) 14) 15 16type PolicyReadCommand struct { 17 *BaseCommand 18} 19 20func (c *PolicyReadCommand) Synopsis() string { 21 return "Prints the contents of a policy" 22} 23 24func (c *PolicyReadCommand) Help() string { 25 helpText := ` 26Usage: vault policy read [options] [NAME] 27 28 Prints the contents and metadata of the Vault policy named NAME. If the policy 29 does not exist, an error is returned. 30 31 Read the policy named "my-policy": 32 33 $ vault policy read my-policy 34 35` + c.Flags().Help() 36 37 return strings.TrimSpace(helpText) 38} 39 40func (c *PolicyReadCommand) Flags() *FlagSets { 41 return c.flagSet(FlagSetHTTP | FlagSetOutputFormat) 42} 43 44func (c *PolicyReadCommand) AutocompleteArgs() complete.Predictor { 45 return c.PredictVaultPolicies() 46} 47 48func (c *PolicyReadCommand) AutocompleteFlags() complete.Flags { 49 return c.Flags().Completions() 50} 51 52func (c *PolicyReadCommand) Run(args []string) int { 53 f := c.Flags() 54 55 if err := f.Parse(args); err != nil { 56 c.UI.Error(err.Error()) 57 return 1 58 } 59 60 args = f.Args() 61 switch { 62 case len(args) < 1: 63 c.UI.Error(fmt.Sprintf("Not enough arguments (expected 1, got %d)", len(args))) 64 return 1 65 case len(args) > 1: 66 c.UI.Error(fmt.Sprintf("Too many arguments (expected 1, got %d)", len(args))) 67 return 1 68 } 69 70 client, err := c.Client() 71 if err != nil { 72 c.UI.Error(err.Error()) 73 return 2 74 } 75 76 name := strings.ToLower(strings.TrimSpace(args[0])) 77 rules, err := client.Sys().GetPolicy(name) 78 if err != nil { 79 c.UI.Error(fmt.Sprintf("Error reading policy named %s: %s", name, err)) 80 return 2 81 } 82 if rules == "" { 83 c.UI.Error(fmt.Sprintf("No policy named: %s", name)) 84 return 2 85 } 86 87 switch Format(c.UI) { 88 case "table": 89 c.UI.Output(strings.TrimSpace(rules)) 90 return 0 91 default: 92 resp := map[string]string{ 93 "policy": rules, 94 } 95 return OutputData(c.UI, &resp) 96 } 97} 98