-
Notifications
You must be signed in to change notification settings - Fork 16
/
userdata.go
307 lines (264 loc) · 8.47 KB
/
userdata.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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
package eks
import (
"encoding/base64"
"errors"
"regexp"
"strings"
"github.com/4armed/kubeletmein/pkg/common"
"github.com/ghodss/yaml"
"github.com/integrii/flaggy"
"github.com/kubicorn/kubicorn/pkg/logger"
"k8s.io/client-go/tools/clientcmd"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
)
// File contains details of files to write through cloud-config
type File struct {
Encoding string `json:"encoding"`
Content string `json:"content"`
Owner string `json:"owner"`
Path string `json:"path"`
Permissions string `json:"permissions"`
}
// CloudConfig contains the parsed cloud-config data
type CloudConfig struct {
WriteFiles []File `json:"write_files"`
}
// ParseUserData takes a string input metadata, works out its type
// and returns a *clientcmdapi.Config ready for marshalling to disk.
func ParseUserData(userData, region string) (*clientcmdapi.Config, error) {
var kubeConfigData *clientcmdapi.Config
// Firstly, is it compressed?
isGzipped, err := common.IsGzipped([]byte(userData))
if err != nil {
return nil, err
}
if isGzipped {
uncompressedData, err := common.GunzipData([]byte(userData))
if err != nil {
return nil, err
}
// update userData
userData = string(uncompressedData)
}
// Is this a cloud-config?
re := regexp.MustCompile(`^#cloud-config`)
match := re.MatchString(userData)
if match {
logger.Debug("assuming gzipped cloud-config")
kubeConfigData, err = ParseCloudConfig([]byte(userData), region)
if err != nil {
return nil, err
}
} else {
logger.Debug("shell script assuming, looking for /etc/eks/bootstrap.sh")
kubeConfigData, err = ParseShellScript(userData)
if err != nil {
return nil, err
}
}
return kubeConfigData, nil
}
// ParseCloudConfig parses gzipped cloud-config formatted YAML from cloud-init
// As a kubelet kubeconfig file is provided we basically pull this out as-is
// from cloud-config but merge in our CA data as `certificate-authority-data`
// to save us having to write out a cert file.
func ParseCloudConfig(cloudConfig []byte, region string) (*clientcmdapi.Config, error) {
var cloudConfigData []byte
k := &clientcmdapi.Config{}
userData := CloudConfig{}
var caData string
// cloud-config is probably gzipped but let's check
gzipped, err := common.IsGzipped(cloudConfig)
if err != nil {
return nil, err
}
if gzipped {
cloudConfigData, err = common.GunzipData(cloudConfig)
if err != nil {
return nil, err
}
} else {
cloudConfigData = cloudConfig
}
err = yaml.Unmarshal(cloudConfigData, &userData)
if err != nil {
return nil, err
}
for _, v := range userData.WriteFiles {
if v.Path == "/etc/eksctl/ca.crt" {
caData = v.Content
}
if v.Path == "/etc/eksctl/kubeconfig.yaml" {
k, err = clientcmd.Load([]byte(v.Content))
if err != nil {
return nil, err
}
}
if v.Path == "/etc/eksctl/kubelet.env" {
kubeletEnvContent := v.Content
re := regexp.MustCompile(`CLUSTER_NAME=(.*)`)
fetchedValue := re.FindStringSubmatch(kubeletEnvContent)
if len(fetchedValue) == 0 {
// different format of cloud-config
continue
}
clusterName := fetchedValue[1]
re = regexp.MustCompile(`API_SERVER_URL=(.*)`)
fetchedValue = re.FindStringSubmatch(kubeletEnvContent)
k8sMaster := fetchedValue[1]
re = regexp.MustCompile(`B64_CLUSTER_CA=(.*)`)
fetchedValue = re.FindStringSubmatch(kubeletEnvContent)
base64EncodedCA := fetchedValue[1]
base64DecodedCAData, err := base64.StdEncoding.DecodeString(base64EncodedCA)
if err != nil {
return nil, err
}
k = &clientcmdapi.Config{
// Define a cluster stanza
Clusters: map[string]*clientcmdapi.Cluster{
clusterName: {
Server: k8sMaster,
CertificateAuthorityData: base64DecodedCAData,
},
},
// Define auth based on the kubelet client cert retrieved
AuthInfos: map[string]*clientcmdapi.AuthInfo{
"kubelet": {
Exec: &clientcmdapi.ExecConfig{
APIVersion: "client.authentication.k8s.io/v1alpha1",
Command: "aws",
Args: []string{
"eks",
"get-token",
"--cluster-name",
clusterName,
"--region",
region,
},
},
},
},
// Define a context and set as current
Contexts: map[string]*clientcmdapi.Context{
"kubeletmein": {
Cluster: clusterName,
AuthInfo: "kubelet",
},
},
CurrentContext: "kubeletmein",
}
}
}
if caData != "" {
contextName := k.CurrentContext
clusterName := k.Contexts[contextName].Cluster
k.Clusters[clusterName].CertificateAuthorityData = []byte(caData)
}
return k, nil
}
// ParseShellScript parses shell-script format user-data seen on managed nodegroups
func ParseShellScript(userData string) (*clientcmdapi.Config, error) {
// We must account for all arguments to bootstrap.sh in order to find the non-flag based cluster name
// https://github.com/awslabs/amazon-eks-ami/blob/master/files/bootstrap.sh
var clusterName = ""
var useMaxPods = ""
var b64ClusterCa = ""
var apiServerEndpoint = ""
var kubeletExtraArgs = ""
var enableDockerBridge = ""
var awsAPIRetryAttempts = ""
var dockerConfigJSON = ""
var pauseContainerAccount = ""
var pauseContainerVersion = ""
var dnsClusterIP = ""
// We are looking for the /etc/eks/boostrap.sh command somewhere in the user-data.
clusterNameAtStart := regexp.MustCompile(`(?m)/etc/eks/bootstrap.sh ([a-z0-9A-Z-_]*)\s*(--.*)`)
eksBootstrapCmd := clusterNameAtStart.FindStringSubmatch(userData)
if eksBootstrapCmd == nil {
return nil, errors.New("error while parsing user-data, could not find /etc/eks/boostrap.sh")
}
eksBootstrapArgs := strings.Fields(eksBootstrapCmd[2])
if eksBootstrapCmd[1] == "" {
// The cluster name must be at the end
clusterName = eksBootstrapArgs[len(eksBootstrapArgs)-1]
// Now remove it
eksBootstrapArgs[len(eksBootstrapArgs)-1] = ""
eksBootstrapArgs = eksBootstrapArgs[:len(eksBootstrapArgs)-1]
} else {
clusterName = eksBootstrapCmd[1]
}
flaggy.ResetParser()
flaggy.String(&useMaxPods, "", "use-max-pods", "")
flaggy.String(&b64ClusterCa, "", "b64-cluster-ca", "")
flaggy.String(&apiServerEndpoint, "", "apiserver-endpoint", "")
flaggy.String(&kubeletExtraArgs, "", "kubelet-extra-args", "")
flaggy.String(&enableDockerBridge, "", "enable-docker-bridge", "")
flaggy.String(&awsAPIRetryAttempts, "", "aws-api-retry-attempts", "")
flaggy.String(&dockerConfigJSON, "", "docker-config-json", "")
flaggy.String(&pauseContainerAccount, "", "pause-container-account", "")
flaggy.String(&pauseContainerVersion, "", "pause-container-version", "")
flaggy.String(&dnsClusterIP, "", "dns-cluster-ip", "")
flaggy.DefaultParser.ShowHelpOnUnexpected = false
flaggy.ParseArgs(eksBootstrapArgs)
logger.Debug("b64ClusterCa: %s", b64ClusterCa)
base64DecodedCAData, err := base64.StdEncoding.DecodeString(checkVariable(b64ClusterCa, userData))
if err != nil {
return nil, err
}
clusterName = checkVariable(clusterName, userData)
k8sMaster := checkVariable(apiServerEndpoint, userData)
kubeconfigData := &clientcmdapi.Config{
// Define a cluster stanza
Clusters: map[string]*clientcmdapi.Cluster{
clusterName: {
Server: k8sMaster,
CertificateAuthorityData: base64DecodedCAData,
},
},
// Define auth based on the kubelet client cert retrieved
AuthInfos: map[string]*clientcmdapi.AuthInfo{
"kubelet": {
Exec: &clientcmdapi.ExecConfig{
APIVersion: "client.authentication.k8s.io/v1alpha1",
Command: "aws",
Args: []string{
"eks",
"get-token",
"--cluster-name",
clusterName,
"--region",
"eu-west-1",
},
Env: []clientcmdapi.ExecEnvVar{
{
Name: "AWS_STS_REGIONAL_ENDPOINTS",
Value: "regional",
},
},
},
},
},
// Define a context and set as current
Contexts: map[string]*clientcmdapi.Context{
"kubeletmein": {
Cluster: clusterName,
AuthInfo: "kubelet",
},
},
CurrentContext: "kubeletmein",
}
return kubeconfigData, nil
}
// Checks if a value looks like a shell variable and, if it is, finds the value in data
func checkVariable(value string, data string) string {
re := regexp.MustCompile(`^\$([a-zA-Z0-9_-]*)`)
variableName := re.FindStringSubmatch(value)
if variableName != nil {
re = regexp.MustCompile(`(?m)^` + regexp.QuoteMeta(variableName[1]) + `=(.*)`)
fetchedValue := re.FindStringSubmatch(data)
value = fetchedValue[1]
}
// Clean up any quotes
unquotedValue := regexp.MustCompile(`^["'](.*)['"]$`).ReplaceAllString(value, `$1`)
return unquotedValue
}