github.com/kunnos/engine@v1.13.1/cli/command/swarm/unlock_key.go (about)

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