-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathunlock_key.go
More file actions
98 lines (80 loc) · 2.3 KB
/
unlock_key.go
File metadata and controls
98 lines (80 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package swarm
import (
"context"
"errors"
"fmt"
"io"
"github.com/docker/cli/cli"
"github.com/docker/cli/cli/command"
"github.com/moby/moby/client"
"github.com/spf13/cobra"
)
type unlockKeyOptions struct {
rotate bool
quiet bool
}
func newUnlockKeyCommand(dockerCLI command.Cli) *cobra.Command {
opts := unlockKeyOptions{}
cmd := &cobra.Command{
Use: "unlock-key [OPTIONS]",
Short: "Manage the unlock key",
Args: cli.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return runUnlockKey(cmd.Context(), dockerCLI, opts)
},
Annotations: map[string]string{
"version": "1.24",
"swarm": "manager",
},
ValidArgsFunction: cobra.NoFileCompletions,
DisableFlagsInUseLine: true,
}
flags := cmd.Flags()
flags.BoolVar(&opts.rotate, flagRotate, false, "Rotate unlock key")
flags.BoolVarP(&opts.quiet, flagQuiet, "q", false, "Only display token")
return cmd
}
func runUnlockKey(ctx context.Context, dockerCLI command.Cli, opts unlockKeyOptions) error {
apiClient := dockerCLI.Client()
if opts.rotate {
res, err := apiClient.SwarmInspect(ctx, client.SwarmInspectOptions{})
if err != nil {
return err
}
if !res.Swarm.Spec.EncryptionConfig.AutoLockManagers {
return errors.New("cannot rotate because autolock is not turned on")
}
_, err = apiClient.SwarmUpdate(ctx, client.SwarmUpdateOptions{
Version: res.Swarm.Version,
Spec: res.Swarm.Spec,
RotateManagerUnlockKey: true,
})
if err != nil {
return err
}
if !opts.quiet {
_, _ = fmt.Fprintln(dockerCLI.Out(), "Successfully rotated manager unlock key.")
}
}
resp, err := apiClient.SwarmGetUnlockKey(ctx)
if err != nil {
return fmt.Errorf("could not fetch unlock key: %w", err)
}
if resp.Key == "" {
return errors.New("no unlock key is set")
}
if opts.quiet {
_, _ = fmt.Fprintln(dockerCLI.Out(), resp.Key)
return nil
}
printUnlockCommand(dockerCLI.Out(), resp.Key)
return nil
}
func printUnlockCommand(out io.Writer, unlockKey string) {
if len(unlockKey) > 0 {
_, _ = fmt.Fprintf(out, "To unlock a swarm manager after it restarts, "+
"run the `docker swarm unlock`\ncommand and provide the following key:\n\n %s\n\n"+
"Remember to store this key in a password manager, since without it you\n"+
"will not be able to restart the manager.\n", unlockKey)
}
}