github.com/itscaro/cli@v0.0.0-20190705081621-c9db0fe93829/cli/command/swarm/unlock_key.go (about) 1 package swarm 2 3 import ( 4 "context" 5 "fmt" 6 "io" 7 8 "github.com/docker/cli/cli" 9 "github.com/docker/cli/cli/command" 10 "github.com/docker/docker/api/types/swarm" 11 "github.com/pkg/errors" 12 "github.com/spf13/cobra" 13 ) 14 15 type unlockKeyOptions struct { 16 rotate bool 17 quiet bool 18 } 19 20 func newUnlockKeyCommand(dockerCli command.Cli) *cobra.Command { 21 opts := unlockKeyOptions{} 22 23 cmd := &cobra.Command{ 24 Use: "unlock-key [OPTIONS]", 25 Short: "Manage the unlock key", 26 Args: cli.NoArgs, 27 RunE: func(cmd *cobra.Command, args []string) error { 28 return runUnlockKey(dockerCli, opts) 29 }, 30 } 31 32 flags := cmd.Flags() 33 flags.BoolVar(&opts.rotate, flagRotate, false, "Rotate unlock key") 34 flags.BoolVarP(&opts.quiet, flagQuiet, "q", false, "Only display token") 35 36 return cmd 37 } 38 39 func runUnlockKey(dockerCli command.Cli, opts unlockKeyOptions) error { 40 client := dockerCli.Client() 41 ctx := context.Background() 42 43 if opts.rotate { 44 flags := swarm.UpdateFlags{RotateManagerUnlockKey: true} 45 46 sw, err := client.SwarmInspect(ctx) 47 if err != nil { 48 return err 49 } 50 51 if !sw.Spec.EncryptionConfig.AutoLockManagers { 52 return errors.New("cannot rotate because autolock is not turned on") 53 } 54 55 if err := client.SwarmUpdate(ctx, sw.Version, sw.Spec, flags); err != nil { 56 return err 57 } 58 59 if !opts.quiet { 60 fmt.Fprintf(dockerCli.Out(), "Successfully rotated manager unlock key.\n\n") 61 } 62 } 63 64 unlockKeyResp, err := client.SwarmGetUnlockKey(ctx) 65 if err != nil { 66 return errors.Wrap(err, "could not fetch unlock key") 67 } 68 69 if unlockKeyResp.UnlockKey == "" { 70 return errors.New("no unlock key is set") 71 } 72 73 if opts.quiet { 74 fmt.Fprintln(dockerCli.Out(), unlockKeyResp.UnlockKey) 75 return nil 76 } 77 78 printUnlockCommand(dockerCli.Out(), unlockKeyResp.UnlockKey) 79 return nil 80 } 81 82 func printUnlockCommand(out io.Writer, unlockKey string) { 83 if len(unlockKey) > 0 { 84 fmt.Fprintf(out, "To unlock a swarm manager after it restarts, "+ 85 "run the `docker swarm unlock`\ncommand and provide the following key:\n\n %s\n\n"+ 86 "Please remember to store this key in a password manager, since without it you\n"+ 87 "will not be able to restart the manager.\n", unlockKey) 88 } 89 }