-
Notifications
You must be signed in to change notification settings - Fork 15
/
etcd_issue.go
93 lines (81 loc) · 2.08 KB
/
etcd_issue.go
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
package cmd
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"github.com/cybozu-go/cke"
"github.com/cybozu-go/well"
"github.com/spf13/cobra"
)
var etcdIssueOpts struct {
TTL string
Output string
}
// etcdIssueCmd represents the "etcd issue" command
var etcdIssueCmd = &cobra.Command{
Use: "issue NAME",
Short: "issue client certificates for a user NAME",
Long: `Issue TLS client certificates for etcd user authentication.
NAME is the username of etcd user to be authenticated.`,
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
username := args[0]
if len(username) == 0 {
return errors.New("username is empty")
}
outputJSON := false
switch etcdIssueOpts.Output {
case "json":
outputJSON = true
case "file":
default:
return errors.New("invalid option: output=" + etcdIssueOpts.Output)
}
well.Go(func(ctx context.Context) error {
cert, key, err := cke.IssueEtcdClientCertificate(inf, username, etcdIssueOpts.TTL)
if err != nil {
return err
}
cacert, err := storage.GetCACertificate(ctx, cke.CAServer)
if err != nil {
return err
}
if outputJSON {
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
return enc.Encode(cke.IssueResponse{
Cert: cert,
Key: key,
CACert: cacert,
})
}
cacertFile := "etcd-ca.crt"
certFile := fmt.Sprintf("etcd-%s.crt", username)
keyFile := fmt.Sprintf("etcd-%s.key", username)
err = os.WriteFile(cacertFile, []byte(cacert), 0644)
if err != nil {
return err
}
err = os.WriteFile(certFile, []byte(cert), 0644)
if err != nil {
return err
}
err = os.WriteFile(keyFile, []byte(key), 0600)
if err != nil {
return err
}
fmt.Println("cert files: ", cacertFile, certFile, keyFile)
return nil
})
well.Stop()
return well.Wait()
},
}
func init() {
fs := etcdIssueCmd.Flags()
fs.StringVar(&etcdIssueOpts.TTL, "ttl", "87600h", "TTL of the certificate")
fs.StringVar(&etcdIssueOpts.Output, "output", "json", `output format ("json" or "file")`)
etcdCmd.AddCommand(etcdIssueCmd)
}