Skip to content

Commit 9728304

Browse files
wip: added dotenv, updated the context logic & docker-compose (#8)
* wip: added dotenv, updated the context logic & docker-compose * wip: added autolabel for adding the labels and updated the log terminal message
1 parent 61f09b7 commit 9728304

File tree

9 files changed

+132
-22
lines changed

9 files changed

+132
-22
lines changed

.env.example

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
CONTEXT=k3d-mycluster

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,5 @@ k8s-custom-controller
33
vendor\
44
.idea
55
.DS_Store
6-
vendor
6+
vendor
7+
.env

controller/controller.go

Lines changed: 45 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,9 @@ func (c *controller) syncDeployment(ns, name string) error {
9191
ObjectMeta: metav1.ObjectMeta{
9292
Name: dep.Name,
9393
Namespace: ns,
94+
//Labels: map[string]string{
95+
//
96+
//},
9497
},
9598
Spec: corev1.ServiceSpec{
9699
Selector: depLabels(*dep),
@@ -102,6 +105,15 @@ func (c *controller) syncDeployment(ns, name string) error {
102105
},
103106
},
104107
}
108+
labels := service.Labels
109+
if labels == nil {
110+
labels = make(map[string]string)
111+
}
112+
labelKey := "rahulxf.io/workload"
113+
if _, exist := labels[labelKey]; !exist {
114+
labels[labelKey] = name
115+
service.SetLabels(labels)
116+
}
105117

106118
_, err = c.clientset.CoreV1().Services(ns).Create(ctx, &service, metav1.CreateOptions{})
107119
if err != nil {
@@ -125,6 +137,9 @@ func (c *controller) createIngress(ns, name string) error {
125137
Annotations: map[string]string{
126138
"nginx.ingress.kubernetes.io/rewrite-target": "/",
127139
},
140+
//Labels: map[string]string{
141+
//
142+
//},
128143
},
129144
Spec: networkingv1.IngressSpec{
130145
Rules: []networkingv1.IngressRule{
@@ -152,6 +167,16 @@ func (c *controller) createIngress(ns, name string) error {
152167
},
153168
},
154169
}
170+
171+
labels := ingress.Labels
172+
if labels == nil {
173+
labels = make(map[string]string)
174+
}
175+
labelKey := "rahulxf.io/workload"
176+
if _, exist := labels[labelKey]; !exist {
177+
labels[labelKey] = name
178+
ingress.SetLabels(labels)
179+
}
155180
_, err := c.clientset.NetworkingV1().Ingresses(ns).Create(ctx, &ingress, metav1.CreateOptions{})
156181
if err != nil {
157182
return err
@@ -166,35 +191,39 @@ func depLabels(dep appsv1.Deployment) map[string]string {
166191

167192
// Almost working
168193
func (c *controller) handleAdd(obj interface{}) {
169-
//fmt.Println("hello add is called")
170-
item, ok := obj.(*appsv1.Deployment)
194+
deployment, ok := obj.(*appsv1.Deployment)
171195
if !ok {
172-
fmt.Println("\n Not a Deployemt")
196+
fmt.Println("\n Not a Deployment")
173197
return
174198
}
175-
fmt.Printf("Deployment \n")
176-
fmt.Printf(item.Name)
177-
fmt.Printf(item.Kind)
178199

179-
fmt.Printf("ADDED: %s", "Kind=%s, Name=%s, Namespace=%s, UID=%s", item.CreationTimestamp,
180-
item.Kind, item.Name, item.Namespace, item.UID)
200+
fmt.Printf("Deployment Added:\n")
201+
fmt.Printf("Name: %s\n", deployment.Name)
202+
203+
fmt.Printf("ADDED: Name=%s, Namespace=%s, UID=%s, Created=%s\n",
204+
deployment.Name,
205+
deployment.Namespace,
206+
string(deployment.UID),
207+
deployment.CreationTimestamp)
181208

182209
c.queue.Add(obj)
183210
}
184211

185212
// Not tested
186213
func (c *controller) handleDel(obj interface{}) {
187-
item, ok := obj.(*appsv1.Deployment)
214+
deployment, ok := obj.(*appsv1.Deployment)
188215
if !ok {
189-
fmt.Println("\n Not a Deployemt")
216+
fmt.Println("\n Not a Deployment")
190217
return
191218
}
192-
fmt.Printf("Deployment \n")
193-
fmt.Printf(item.Name)
194-
fmt.Printf(item.Kind)
219+
fmt.Printf("Deployment Deleted:\n")
220+
fmt.Printf("Name: %s\n", deployment.Name)
195221

196-
fmt.Printf("DELETED: %s", "Kind=%s, Name=%s, Namespace=%s, UID=%s", item.CreationTimestamp,
197-
item.Kind, item.Name, item.Namespace, item.UID)
222+
fmt.Printf("DELETED: Name=%s, Namespace=%s, UID=%s, Created=%s\n",
223+
deployment.Name,
224+
deployment.Namespace,
225+
string(deployment.UID),
226+
deployment.CreationTimestamp)
198227

199-
c.queue.Add(obj)
228+
//c.queue.Add(obj)
200229
}

docker-compose.yml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,6 @@ services:
66
volumes:
77
- ${HOME}/.kube:/root/.kube
88
network_mode: "host"
9-
# ports:
10-
# - "8000:8000"
9+
env_file:
10+
- .env
1111

go.mod

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ go 1.24.0
55
toolchain go1.24.3
66

77
require (
8+
github.com/joho/godotenv v1.5.1
89
k8s.io/api v0.33.0
910
k8s.io/apimachinery v0.33.0
1011
k8s.io/client-go v0.33.0

go.sum

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@ github.com/google/pprof v0.0.0-20241029153458-d1b30febd7db h1:097atOisP2aRj7vFgY
3131
github.com/google/pprof v0.0.0-20241029153458-d1b30febd7db/go.mod h1:vavhavw2zAxS5dIdcRluK6cSGGPlZynqzFM8NdvU144=
3232
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
3333
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
34+
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
35+
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
3436
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
3537
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
3638
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=

guide.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
```go
2+
docker run --rm --name k8s-custom-controller \
3+
--network host \
4+
-v $HOME/.kube:/root/.kube \
5+
k8s-custom-controller-controller:latest
6+
7+
```
8+
```go
9+
kubectl create deployment my-deployment --image=nginx:latest --labels=app=nginx,env=prod
10+
```

main.go

Lines changed: 44 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,16 @@ package main
22

33
import (
44
"fmt"
5+
"github.com/joho/godotenv"
56
"github.com/manzil-infinity180/k8s-custom-controller/controller"
67
"k8s.io/client-go/dynamic"
78
"k8s.io/client-go/informers"
89
"k8s.io/client-go/kubernetes"
910
"k8s.io/client-go/tools/clientcmd"
11+
"k8s.io/client-go/tools/clientcmd/api"
12+
"log"
1013
"os"
14+
"strings"
1115
"time"
1216
)
1317

@@ -19,6 +23,35 @@ func homeDir() string {
1923
return os.Getenv("USERPROFILE") // Windows
2024
}
2125

26+
func ListContexts() (string, []string, error) {
27+
config, err := getKubeConfig()
28+
if err != nil {
29+
return "", nil, err
30+
}
31+
currentContext := config.CurrentContext
32+
var contexts []string
33+
for name := range config.Contexts {
34+
if strings.Contains(name, "wds") {
35+
contexts = append(contexts, name)
36+
}
37+
}
38+
return currentContext, contexts, nil
39+
}
40+
func getKubeConfig() (*api.Config, error) {
41+
kubeconfig := os.Getenv("KUBECONFIG")
42+
if kubeconfig == "" {
43+
if home := homeDir(); home != "" {
44+
kubeconfig = fmt.Sprintf("%s/.kube/config", home)
45+
}
46+
}
47+
48+
config, err := clientcmd.LoadFromFile(kubeconfig)
49+
if err != nil {
50+
return nil, err
51+
}
52+
return config, nil
53+
}
54+
2255
// GetClientSetWithContext retrieves a Kubernetes clientset and dynamic client for a specified context
2356
func GetClientSetWithContext(contextName string) (*kubernetes.Clientset, dynamic.Interface, error) {
2457
kubeconfig := os.Getenv("KUBECONFIG")
@@ -33,7 +66,10 @@ func GetClientSetWithContext(contextName string) (*kubernetes.Clientset, dynamic
3366
if err != nil {
3467
return nil, nil, fmt.Errorf("failed to load kubeconfig: %v", err)
3568
}
36-
69+
// if user does not mention any context then we will be using the current-system-context
70+
if contextName == "" {
71+
contextName = config.CurrentContext
72+
}
3773
// Check if the specified context exists
3874
ctxContext := config.Contexts[contextName]
3975
if ctxContext == nil {
@@ -65,8 +101,13 @@ func GetClientSetWithContext(contextName string) (*kubernetes.Clientset, dynamic
65101
return clientset, dynamicClient, nil
66102
}
67103
func main() {
68-
// add your context here
69-
clientset, _, err := GetClientSetWithContext("cluster1")
104+
// add your context in the docker-compose.yml
105+
if err := godotenv.Load(); err != nil {
106+
log.Println(".env file not found, assuming environment variables are set")
107+
}
108+
context := os.Getenv("CONTEXT")
109+
fmt.Println(context)
110+
clientset, _, err := GetClientSetWithContext(context)
70111
if err != nil {
71112
fmt.Println()
72113
fmt.Errorf("%s", err.Error())

manifest/examples/deployment.yaml

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
apiVersion: apps/v1
2+
kind: Deployment
3+
metadata:
4+
name: my-deployment2
5+
labels:
6+
app: nginx
7+
env: prod
8+
"rahulxf.io/workload": my-deployment2
9+
spec:
10+
replicas: 1
11+
selector:
12+
matchLabels:
13+
app: nginx
14+
"rahulxf.io/workload": my-deployment2
15+
template:
16+
metadata:
17+
labels:
18+
app: nginx
19+
env: prod
20+
"rahulxf.io/workload": my-deployment2
21+
spec:
22+
containers:
23+
- name: nginx
24+
image: nginx:latest
25+

0 commit comments

Comments
 (0)