-
Notifications
You must be signed in to change notification settings - Fork 90
/
cluster.go
57 lines (47 loc) · 1.89 KB
/
cluster.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
package k8sutil
import (
"context"
"fmt"
"github.com/pkg/errors"
"k8s.io/client-go/kubernetes"
"time"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
bootstrapapi "k8s.io/cluster-bootstrap/token/api"
bootstraputil "k8s.io/cluster-bootstrap/token/util"
)
// GenerateBootstrapToken will generate a node join token for kubeadm.
// ttl defines the time to live for this token.
func GenerateBootstrapToken(client kubernetes.Interface, ttl time.Duration) (string, error) {
token, err := bootstraputil.GenerateBootstrapToken()
if err != nil {
return "", errors.Wrap(err, "generate kubeadm token")
}
substrs := bootstraputil.BootstrapTokenRegexp.FindStringSubmatch(token)
tokenID := substrs[1]
tokenSecret := substrs[2]
data := map[string][]byte{
bootstrapapi.BootstrapTokenIDKey: []byte(tokenID),
bootstrapapi.BootstrapTokenSecretKey: []byte(tokenSecret),
}
data[bootstrapapi.BootstrapTokenDescriptionKey] = []byte("Token auto generated by Kotsadm.")
expirationString := time.Now().Add(ttl).UTC().Format(time.RFC3339)
data[bootstrapapi.BootstrapTokenExpirationKey] = []byte(expirationString)
for _, usage := range []string{"authentication", "signing"} {
data[bootstrapapi.BootstrapTokenUsagePrefix+usage] = []byte("true")
}
data[bootstrapapi.BootstrapTokenExtraGroupsKey] = []byte("system:bootstrappers:kubeadm:default-node-token")
secretName := fmt.Sprintf("%s%s", bootstrapapi.BootstrapTokenSecretPrefix, tokenID)
bootstrapToken := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: secretName,
Namespace: metav1.NamespaceSystem,
},
Type: bootstrapapi.SecretTypeBootstrapToken,
Data: data,
}
if _, err := client.CoreV1().Secrets(metav1.NamespaceSystem).Create(context.TODO(), bootstrapToken, metav1.CreateOptions{}); err != nil {
return "", errors.Wrapf(err, "failed to create bootstrap token with name %s", secretName)
}
return token, nil
}