-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.go
257 lines (224 loc) · 6.26 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
/*
Copyright 2021 Sergio Rua
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"flag"
"log"
"os"
"path/filepath"
"regexp"
"strings"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
)
var verbose bool
var local bool
var kubeconfig string
func init() {
flag.BoolVar(&verbose, "v", false, "Verbose")
flag.BoolVar(&local, "l", false, "Run outside kube cluster (dev purposes)")
if home := homeDir(); home != "" {
flag.StringVar(&kubeconfig, "kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
} else {
flag.StringVar(&kubeconfig, "kubeconfig", "", "absolute path to the kubeconfig file")
}
}
func main() {
flag.Parse()
var config *rest.Config
var err error
// local = true
if local == false {
config, err = rest.InClusterConfig()
if err != nil {
panic(err.Error())
}
} else {
config, err = clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
panic(err.Error())
}
}
// create the clientset
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
log.Fatalln(err.Error())
}
watcher, err := clientset.CoreV1().PersistentVolumeClaims("").Watch(metav1.ListOptions{})
if err != nil {
log.Fatalln(err)
}
/* changes */
ch := watcher.ResultChan()
for event := range ch {
pvc, ok := event.Object.(*v1.PersistentVolumeClaim)
if !ok {
log.Fatal("unexpected type")
}
if event.Type == watch.Added || event.Type == watch.Modified {
namespace := pvc.GetNamespace()
volumeClaimName := pvc.GetName()
volumeClaim := *pvc
if isVolumeSupported(&volumeClaim) {
volumeName := volumeClaim.Spec.VolumeName
awsVolume, errp := clientset.CoreV1().PersistentVolumes().Get(volumeName, metav1.GetOptions{})
if errp != nil {
log.Printf("Cannot find EBS volume associated with %s: %s", volumeName, errp)
continue
}
awsVolumeID := awsVolume.Spec.PersistentVolumeSource.AWSElasticBlockStore.VolumeID
log.Printf("Volume Claim: %s\n", volumeClaimName)
log.Printf("\tEvent Type: %s", event.Type)
log.Printf("\tNamespace: %s\n", namespace)
log.Printf("\tVolume: %s\n", volumeName)
log.Printf("\tAWS Volume ID: %s\n", awsVolumeID)
separator := ","
tagsToAdd := ""
for k, v := range volumeClaim.Annotations {
if k == "volume.beta.kubernetes.io/additional-resource-tags-separator" {
separator = v
}
if k == "volume.beta.kubernetes.io/additional-resource-tags" {
tagsToAdd = v
}
}
if tagsToAdd != "" {
addAWSTags(tagsToAdd, awsVolumeID, separator)
}
} else {
log.Printf("\t=> Volume %s is not of a supported type. Ignoring", volumeClaim.Spec.VolumeName)
}
}
}
}
/*
This only works for some volumes. NFS volumes for example cannot be be tagged.
*/
func isVolumeSupported(volume *v1.PersistentVolumeClaim) bool {
for k, v := range volume.Annotations {
if (k == "volume.beta.kubernetes.io/storage-provisioner" && v == "kubernetes.io/aws-ebs") ||
(k == "pv.kubernetes.io/provisioned-by" && strings.Contains(v, "ebs.csi.aws.com")) ||
(k == "volume.beta.kubernetes.io/storage-provisioner" && strings.Contains(v, "ebs.csi.aws.com")) {
return true
}
}
return false
}
/*
Loops through the tags found for the volume and calls `setTag`
to add it via the AWS api
*/
func addAWSTags(awsTags string, awsVolumeID string, separator string) {
awsRegion, awsVolume := splitVol(awsVolumeID)
/* Connect to AWS */
sess, err := session.NewSession(&aws.Config{
Region: aws.String(awsRegion),
})
if err != nil {
panic(err)
}
svc := ec2.New(sess)
params := &ec2.DescribeVolumesInput{
VolumeIds: []*string{&awsVolume},
}
resp, err := svc.DescribeVolumes(params)
if err != nil {
log.Printf("Cannot get volume %s", awsVolume)
log.Println(err)
return
}
tags := strings.Split(awsTags, separator)
for i := range tags {
log.Printf("\tAdding tag %s to EBS Volume %s\n", tags[i], awsVolume)
t := strings.Split(tags[i], "=")
if len(t) != 2 {
log.Printf("Malformed tag found, skipping: %v", t)
continue
}
if !hasTag(resp.Volumes[0].Tags, t[0], t[1]) {
setTag(svc, t[0], t[1], awsVolume)
}
}
}
/*
AWS api call to set the tag found in the annotations
*/
func setTag(svc *ec2.EC2, tagKey string, tagValue string, volumeID string) bool {
tags := &ec2.CreateTagsInput{
Resources: []*string{
aws.String(volumeID),
},
Tags: []*ec2.Tag{
{
Key: aws.String(tagKey),
Value: aws.String(tagValue),
},
},
}
ret, err := svc.CreateTags(tags)
if err != nil {
log.Fatal(err)
return false
}
if verbose {
log.Println(ret)
}
return true
}
/*
Check if the tag is already set. It wouldn't be a problem if it is
but if you're using cloudtrail it may be an issue seeing it
being set all muiltiple times
*/
func hasTag(tags []*ec2.Tag, Key string, value string) bool {
for i := range tags {
if *tags[i].Key == Key && *tags[i].Value == value {
log.Printf("\t\tTag %s already set with value %s\n",
*tags[i].Key,
*tags[i].Value)
return true
}
}
return false
}
/* Take a URL as returned by Kubernetes in the format
aws://eu-west-1b/vol-7iyw8ygidg
and returns region and volume name
*/
func splitVol(vol string) (string, string) {
sp := strings.Split(vol, "/")
re := regexp.MustCompile(`[a-z]$`)
zone := re.ReplaceAllString(sp[2], "")
return zone, sp[3]
}
func stringInSlice(str string, list []string) bool {
for _, v := range list {
if v == str {
return true
}
}
return false
}
func homeDir() string {
if h := os.Getenv("HOME"); h != "" {
return h
}
return os.Getenv("USERPROFILE") // windows
}