github.com/marwan-at-work/consul@v1.4.5/command/connect/ca/set/connect_ca_set.go (about)

     1  package set
     2  
     3  import (
     4  	"encoding/json"
     5  	"flag"
     6  	"fmt"
     7  	"io/ioutil"
     8  
     9  	"github.com/hashicorp/consul/api"
    10  	"github.com/hashicorp/consul/command/flags"
    11  	"github.com/mitchellh/cli"
    12  )
    13  
    14  func New(ui cli.Ui) *cmd {
    15  	c := &cmd{UI: ui}
    16  	c.init()
    17  	return c
    18  }
    19  
    20  type cmd struct {
    21  	UI    cli.Ui
    22  	flags *flag.FlagSet
    23  	http  *flags.HTTPFlags
    24  	help  string
    25  
    26  	// flags
    27  	configFile flags.StringValue
    28  }
    29  
    30  func (c *cmd) init() {
    31  	c.flags = flag.NewFlagSet("", flag.ContinueOnError)
    32  	c.flags.Var(&c.configFile, "config-file",
    33  		"The path to the config file to use.")
    34  
    35  	c.http = &flags.HTTPFlags{}
    36  	flags.Merge(c.flags, c.http.ClientFlags())
    37  	flags.Merge(c.flags, c.http.ServerFlags())
    38  	c.help = flags.Usage(help, c.flags)
    39  }
    40  
    41  func (c *cmd) Run(args []string) int {
    42  	if err := c.flags.Parse(args); err != nil {
    43  		if err == flag.ErrHelp {
    44  			return 0
    45  		}
    46  		c.UI.Error(fmt.Sprintf("Failed to parse args: %v", err))
    47  		return 1
    48  	}
    49  
    50  	// Set up a client.
    51  	client, err := c.http.APIClient()
    52  	if err != nil {
    53  		c.UI.Error(fmt.Sprintf("Error initializing client: %s", err))
    54  		return 1
    55  	}
    56  
    57  	if c.configFile.String() == "" {
    58  		c.UI.Error("The -config-file flag is required")
    59  		return 1
    60  	}
    61  
    62  	bytes, err := ioutil.ReadFile(c.configFile.String())
    63  	if err != nil {
    64  		c.UI.Error(fmt.Sprintf("Error reading config file: %s", err))
    65  		return 1
    66  	}
    67  
    68  	var config api.CAConfig
    69  	if err := json.Unmarshal(bytes, &config); err != nil {
    70  		c.UI.Error(fmt.Sprintf("Error parsing config file: %s", err))
    71  		return 1
    72  	}
    73  
    74  	// Set the new configuration.
    75  	if _, err := client.Connect().CASetConfig(&config, nil); err != nil {
    76  		c.UI.Error(fmt.Sprintf("Error setting CA configuration: %s", err))
    77  		return 1
    78  	}
    79  	c.UI.Output("Configuration updated!")
    80  	return 0
    81  }
    82  
    83  func (c *cmd) Synopsis() string {
    84  	return synopsis
    85  }
    86  
    87  func (c *cmd) Help() string {
    88  	return c.help
    89  }
    90  
    91  const synopsis = "Modify the current Connect CA configuration"
    92  const help = `
    93  Usage: consul connect ca set-config [options]
    94  
    95    Modifies the current Connect Certificate Authority (CA) configuration.
    96  `