github.com/blixtra/nomad@v0.7.2-0.20171221000451-da9a1d7bb050/command/acl_policy_apply.go (about) 1 package command 2 3 import ( 4 "fmt" 5 "io/ioutil" 6 "os" 7 "strings" 8 9 "github.com/hashicorp/nomad/api" 10 "github.com/posener/complete" 11 ) 12 13 type ACLPolicyApplyCommand struct { 14 Meta 15 } 16 17 func (c *ACLPolicyApplyCommand) Help() string { 18 helpText := ` 19 Usage: nomad acl policy apply [options] <name> <path> 20 21 Apply is used to create or update an ACL policy. The policy is 22 sourced from <path> or from stdin if path is "-". 23 24 General Options: 25 26 ` + generalOptionsUsage() + ` 27 28 Apply Options: 29 30 -description 31 Specifies a human readable description for the policy. 32 33 ` 34 return strings.TrimSpace(helpText) 35 } 36 37 func (c *ACLPolicyApplyCommand) AutocompleteFlags() complete.Flags { 38 return mergeAutocompleteFlags(c.Meta.AutocompleteFlags(FlagSetClient), 39 complete.Flags{}) 40 } 41 42 func (c *ACLPolicyApplyCommand) AutocompleteArgs() complete.Predictor { 43 return complete.PredictNothing 44 } 45 46 func (c *ACLPolicyApplyCommand) Synopsis() string { 47 return "Create or update an ACL policy" 48 } 49 50 func (c *ACLPolicyApplyCommand) Run(args []string) int { 51 var description string 52 flags := c.Meta.FlagSet("acl policy apply", FlagSetClient) 53 flags.Usage = func() { c.Ui.Output(c.Help()) } 54 flags.StringVar(&description, "description", "", "") 55 if err := flags.Parse(args); err != nil { 56 return 1 57 } 58 59 // Check that we got two arguments 60 args = flags.Args() 61 if l := len(args); l != 2 { 62 c.Ui.Error(c.Help()) 63 return 1 64 } 65 66 // Get the policy name 67 policyName := args[0] 68 69 // Read the file contents 70 file := args[1] 71 var rawPolicy []byte 72 var err error 73 if file == "-" { 74 rawPolicy, err = ioutil.ReadAll(os.Stdin) 75 if err != nil { 76 c.Ui.Error(fmt.Sprintf("Failed to read stdin: %v", err)) 77 return 1 78 } 79 } else { 80 rawPolicy, err = ioutil.ReadFile(file) 81 if err != nil { 82 c.Ui.Error(fmt.Sprintf("Failed to read file: %v", err)) 83 return 1 84 } 85 } 86 87 // Construct the policy 88 ap := &api.ACLPolicy{ 89 Name: policyName, 90 Description: description, 91 Rules: string(rawPolicy), 92 } 93 94 // Get the HTTP client 95 client, err := c.Meta.Client() 96 if err != nil { 97 c.Ui.Error(fmt.Sprintf("Error initializing client: %s", err)) 98 return 1 99 } 100 101 // Upsert the policy 102 _, err = client.ACLPolicies().Upsert(ap, nil) 103 if err != nil { 104 c.Ui.Error(fmt.Sprintf("Error writing ACL policy: %s", err)) 105 return 1 106 } 107 108 c.Ui.Output(fmt.Sprintf("Successfully wrote %q ACL policy!", 109 policyName)) 110 return 0 111 }