-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
172 lines (153 loc) · 4.63 KB
/
main.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
// This program uses the Kubernetes client-go library to create a new token using the TokenRequest API, and then creates a
// kubeconfig file using the token.
package main
import (
"context"
"encoding/base64"
"flag"
"fmt"
"log"
"os"
"path/filepath"
"gopkg.in/yaml.v2"
authv1 "k8s.io/api/authentication/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
)
// Cluster holds the cluster data
type Cluster struct {
CertificateAuthorityData string `yaml:"certificate-authority-data"`
Server string `yaml:"server"`
}
// Clusters hold an array of the clusters that would exist in the config file
type Clusters []struct {
Cluster Cluster `yaml:"cluster"`
Name string `yaml:"name"`
}
// Context holds the cluster context
type Context struct {
Cluster string `yaml:"cluster"`
User string `yaml:"user"`
}
// Contexts holds an array of the contexts
type Contexts []struct {
Context Context `yaml:"context"`
Name string `yaml:"name"`
}
// Users holds an array of the users that would exist in the config file
type Users []struct {
User User `yaml:"user"`
Name string `yaml:"name"`
}
// User holds the user authentication data
type User struct {
Token string `yaml:"token"`
}
// KubeConfig holds the necessary data for creating a new KubeConfig file
type KubeConfig struct {
APIVersion string `yaml:"apiVersion"`
Clusters Clusters `yaml:"clusters"`
Contexts Contexts `yaml:"contexts"`
CurrentContext string `yaml:"current-context"`
Kind string `yaml:"kind"`
Preferences struct{} `yaml:"preferences"`
Users Users `yaml:"users"`
}
func initKubeClient() (*kubernetes.Clientset, clientcmd.ClientConfig, error) {
loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
kubeConfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, &clientcmd.ConfigOverrides{})
config, err := kubeConfig.ClientConfig()
if err != nil {
log.Printf("initKubeClient: failed creating ClientConfig with %s\n", err)
return nil, nil, err
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
log.Printf("initKubeClient: failed creating Clientset with %s\n", err)
return nil, nil, err
}
return clientset, kubeConfig, nil
}
func main() {
serviceAccountName := flag.String("service-account", "default", "The service account to use for the token")
namespace := flag.String("namespace", "default", "The namespace to use for the token")
outputFile := flag.String("output-file", "", "The name of the kubeconfig file to create")
expirationSeconds := flag.Int64("expiration-seconds", 3600, "The expiration time of the token in seconds")
flag.Parse()
if *outputFile == "" {
*outputFile = *serviceAccountName + ".kubeconfig"
}
clientset, kubeConfig, err := initKubeClient()
if err != nil {
log.Fatal("error initializing kubernetes client")
}
raw, err := kubeConfig.RawConfig()
if err != nil {
log.Fatalf("Error creating Kubeconfig %s", err)
}
cluster := raw.Contexts[raw.CurrentContext].Cluster
tokenRequest := &authv1.TokenRequest{
ObjectMeta: metav1.ObjectMeta{
Name: *serviceAccountName,
Namespace: *namespace,
},
Spec: authv1.TokenRequestSpec{
ExpirationSeconds: expirationSeconds,
},
}
result, err := clientset.CoreV1().ServiceAccounts(*namespace).CreateToken(context.TODO(), *serviceAccountName, tokenRequest, metav1.CreateOptions{})
if err != nil {
log.Fatalf("Error in creating Token %s", err)
}
kc := &KubeConfig{
APIVersion: "v1",
Clusters: Clusters{
0: {
Cluster{
base64.StdEncoding.EncodeToString([]byte(raw.Clusters[cluster].CertificateAuthorityData)),
raw.Clusters[cluster].Server,
},
cluster,
},
},
Contexts: Contexts{
0: {
Context{
Cluster: cluster,
User: *serviceAccountName,
},
cluster,
},
},
CurrentContext: cluster,
Kind: "Config",
Users: Users{
0: {
User{
Token: result.Status.Token,
},
*serviceAccountName,
},
},
}
dir, err := os.Getwd()
if err != nil {
log.Fatalf("Error Getting working directory %s", err)
}
_, err = os.Create(filepath.Join(dir, *outputFile))
if err != nil {
log.Fatalf("Error Creating output file %s", err)
}
file, err := os.OpenFile(*outputFile, os.O_APPEND|os.O_WRONLY, os.ModeAppend)
if err != nil {
log.Fatalf("Error opening output file %s", err)
}
defer file.Close()
e := yaml.NewEncoder(file)
err = e.Encode(kc)
if err != nil {
log.Fatalf("Error encoding Kubeconfig YAML %s", err)
}
fmt.Printf("Kubeconfig file %s created for service account %s in namespace %s \n", *outputFile, *serviceAccountName, *namespace)
}