-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
263 lines (229 loc) · 7.32 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
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
package main
import (
"context"
"encoding/base64"
"fmt"
"os"
"github.com/aws/aws-lambda-go/cfn"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/eks"
"github.com/kubernetes-sigs/aws-iam-authenticator/pkg/token"
yaml "gopkg.in/yaml.v2"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
type cluster struct {
Name string
Endpoint string
CA []byte
MasterRole string
}
type mapRolesData []map[string]interface{}
const (
//configMapNamespace is the namespace of the ConfigMap
configMapNamespace = "kube-system"
//configMapName is the name of the ConfigMap
configMapName = "aws-auth"
)
func getClusterInfo(clustername string, masterroleARN string, region string) (*cluster, error) {
sess, err := session.NewSession(&aws.Config{Region: aws.String(region)})
svc := eks.New(sess)
input := &eks.DescribeClusterInput{
Name: aws.String(clustername),
}
result, err := svc.DescribeCluster(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case eks.ErrCodeResourceNotFoundException:
fmt.Println(eks.ErrCodeResourceNotFoundException, aerr.Error())
case eks.ErrCodeClientException:
fmt.Println(eks.ErrCodeClientException, aerr.Error())
case eks.ErrCodeServerException:
fmt.Println(eks.ErrCodeServerException, aerr.Error())
case eks.ErrCodeServiceUnavailableException:
fmt.Println(eks.ErrCodeServiceUnavailableException, aerr.Error())
default:
fmt.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
fmt.Println(err.Error())
}
return nil, err
}
// The CA data comes base64 encoded string inside a JSON object { "Data": "..." }
ca, err := base64.StdEncoding.DecodeString(*result.Cluster.CertificateAuthority.Data)
if err != nil {
return nil, err
}
return &cluster{
Name: *result.Cluster.Name,
Endpoint: *result.Cluster.Endpoint,
CA: ca,
MasterRole: masterroleARN,
}, nil
}
func (c *cluster) AuthToken() (string, error) {
// Init a new aws-iam-authenticator token generator
gen, err := token.NewGenerator()
if err != nil {
return "", err
}
// Use the current IAM credentials to obtain a K8s bearer token
tok, err := gen.GetWithRole(c.Name, c.MasterRole)
if err != nil {
return "", err
}
return tok, nil
}
// Handler is your Lambda function handler
func Handler(ctx context.Context, event cfn.Event) (physicalResourceID string, data map[string]interface{}, err error) {
//Print CloudFormation request
fmt.Println(event)
// Request variables
clustername := event.ResourceProperties["ClusterName"].(string)
if len(clustername) < 1 {
panic("Unable to grab cluster name from ENVIRONMENT variable")
}
masterroleARN := event.ResourceProperties["MasterRoleARN"].(string)
if len(masterroleARN) < 1 {
panic("Unable to grab Master Role ARN from ENVIRONMENT variable")
}
nodeInstRoleARN := event.ResourceProperties["NodeInstanceRoleARN"].(string)
if len(nodeInstRoleARN) < 1 {
panic("Unable to grab Node Instance Role ARN from ENVIRONMENT variable")
}
// Get Region info from Resource Properties or lambda env
region := event.ResourceProperties["AWS_REGION"].(string)
if len(region) < 1 {
fmt.Printf("Resource Properties does not have AWS_REGION, pick default from Lambda environment")
region = os.Getenv("AWS_REGION")
}
// Get EKS cluster details
cluster, err := getClusterInfo(clustername, masterroleARN, region)
fmt.Printf("Amazon EKS Cluster: %s (%s)\n", cluster.Name, cluster.Endpoint)
// Use the aws-iam-authenticator to fetch a K8s authentication bearer token
token, err := cluster.AuthToken()
if err != nil {
panic("Failed to obtain token from aws-iam-authenticator, " + err.Error())
}
// Create a new K8s client set using the Amazon EKS cluster details
clientSet, err := kubernetes.NewForConfig(&rest.Config{
Host: cluster.Endpoint,
BearerToken: token,
TLSClientConfig: rest.TLSClientConfig{
CAData: cluster.CA,
},
})
if err != nil {
fmt.Printf("Failed to create new k8s client")
return "", nil, err
}
//CreateOrUpdateNodeGroupAuthConfigMap
createOrUpdateAuthConfigMap, err := createOrUpdateNodeInstRoleAuthConfigMap(clientSet, nodeInstRoleARN)
if err != nil {
return "", nil, err
}
data = map[string]interface{}{
"Created/Updated ConfigMap": createOrUpdateAuthConfigMap,
}
//Adding physcialResourceID as LogStream keeps changing
physicalResourceID = "CreateOrUpdateConfigMapWithNodeInstanceRole"
return
}
//CreateOrUpdateNodeInstRoleAuthConfigMap to modify aws-auth
func createOrUpdateNodeInstRoleAuthConfigMap(clientset *kubernetes.Clientset, nodeInstRoleARN string) (bool, error) {
configMap := &corev1.ConfigMap{}
client := clientset.CoreV1().ConfigMaps(configMapNamespace)
create := false
if existing, err := client.Get(configMapName, metav1.GetOptions{}); err != nil {
if errors.IsNotFound(err) {
create = true
} else {
return false, err
}
} else {
*configMap = *existing
}
if create {
configMap, err := NewAuthConfigMap(nodeInstRoleARN)
if err != nil {
return false, err
}
if _, err := client.Create(configMap); err != nil {
return false, err
}
fmt.Printf("created auth ConfigMap")
return false, nil
}
if err := UpdateAuthConfigMap(configMap, nodeInstRoleARN); err != nil {
return false, err
}
if _, err := client.Update(configMap); err != nil {
return false, err
}
fmt.Printf("updated auth ConfigMap")
return true, nil
}
func makeMapRolesData() mapRolesData { return []map[string]interface{}{} }
func appendNodeInstRoleARNToAuthConfigMap(mapRoles *mapRolesData, nodeInstRoleARN string) {
newEntry := map[string]interface{}{
"rolearn": nodeInstRoleARN,
"username": "system:node:{{EC2PrivateDNSName}}",
"groups": []string{
"system:bootstrappers",
"system:nodes",
},
}
*mapRoles = append(*mapRoles, newEntry)
}
func newAuthConfigMap(mapRoles mapRolesData) (*corev1.ConfigMap, error) {
mapRolesBytes, err := yaml.Marshal(mapRoles)
if err != nil {
return nil, err
}
cm := &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: configMapName,
Namespace: configMapNamespace,
},
Data: map[string]string{
"mapRoles": string(mapRolesBytes),
},
}
return cm, nil
}
// NewAuthConfigMap creates ConfigMap with a single nodegroup ARN
func NewAuthConfigMap(nodeInstRoleARN string) (*corev1.ConfigMap, error) {
mapRoles := makeMapRolesData()
appendNodeInstRoleARNToAuthConfigMap(&mapRoles, nodeInstRoleARN)
return newAuthConfigMap(mapRoles)
}
func updateAuthConfigMap(cm *corev1.ConfigMap, mapRoles mapRolesData) error {
mapRolesBytes, err := yaml.Marshal(mapRoles)
if err != nil {
return err
}
cm.Data["mapRoles"] = string(mapRolesBytes)
return nil
}
// UpdateAuthConfigMap updates ConfigMap by appending a single nodegroup ARN
func UpdateAuthConfigMap(cm *corev1.ConfigMap, nodeInstRoleARN string) error {
mapRoles := makeMapRolesData()
if err := yaml.Unmarshal([]byte(cm.Data["mapRoles"]), &mapRoles); err != nil {
return err
}
appendNodeInstRoleARNToAuthConfigMap(&mapRoles, nodeInstRoleARN)
return updateAuthConfigMap(cm, mapRoles)
}
func main() {
lambda.Start(cfn.LambdaWrap(Handler))
}