Add -check flag to init.

Fixes #949
This commit is contained in:
Jeff Mitchell 2016-01-22 13:06:40 -05:00
parent babecad8ac
commit d95adc731a
2 changed files with 67 additions and 0 deletions

View File

@ -16,10 +16,12 @@ type InitCommand struct {
func (c *InitCommand) Run(args []string) int {
var threshold, shares int
var pgpKeys pgpkeys.PubKeyFilesFlag
var check bool
flags := c.Meta.FlagSet("init", FlagSetDefault)
flags.Usage = func() { c.Ui.Error(c.Help()) }
flags.IntVar(&shares, "key-shares", 5, "")
flags.IntVar(&threshold, "key-threshold", 3, "")
flags.BoolVar(&check, "check", false, "")
flags.Var(&pgpKeys, "pgp-keys", "")
if err := flags.Parse(args); err != nil {
return 1
@ -32,6 +34,10 @@ func (c *InitCommand) Run(args []string) int {
return 1
}
if check {
return c.checkStatus(client)
}
resp, err := client.Sys().Init(&api.InitRequest{
SecretShares: shares,
SecretThreshold: threshold,
@ -66,6 +72,22 @@ func (c *InitCommand) Run(args []string) int {
return 0
}
func (c *InitCommand) checkStatus(client *api.Client) int {
inited, err := client.Sys().InitStatus()
switch {
case err != nil:
c.Ui.Error(fmt.Sprintf(
"Error checking initialization status: %s", err))
return 1
case inited:
c.Ui.Output("Vault has been initialized")
return 0
default:
c.Ui.Output("Vault is not initialized")
return 2
}
}
func (c *InitCommand) Synopsis() string {
return "Initialize a new Vault server"
}
@ -88,6 +110,12 @@ General Options:
Init Options:
-check Don't actually initialize, just check if Vault is
already initialized. A return code of 0 means Vault
is initialized; a return code of 2 means Vault is not
initialized; a return code of 1 means an error was
encountered.
-key-shares=5 The number of key shares to split the master key
into.

View File

@ -58,6 +58,45 @@ func TestInit(t *testing.T) {
}
}
func TestInit_Check(t *testing.T) {
ui := new(cli.MockUi)
c := &InitCommand{
Meta: Meta{
Ui: ui,
},
}
core := vault.TestCore(t)
ln, addr := http.TestServer(t, core)
defer ln.Close()
// Should return 2, not initialized
args := []string{"-address", addr, "-check"}
if code := c.Run(args); code != 2 {
t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String())
}
// Now initialize it
args = []string{"-address", addr}
if code := c.Run(args); code != 0 {
t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String())
}
// Should return 0, initialized
args = []string{"-address", addr, "-check"}
if code := c.Run(args); code != 0 {
t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String())
}
init, err := core.Initialized()
if err != nil {
t.Fatalf("err: %s", err)
}
if !init {
t.Fatal("should be initialized")
}
}
func TestInit_custom(t *testing.T) {
ui := new(cli.MockUi)
c := &InitCommand{