1
1
import json
2
2
import logging
3
+ import os
3
4
4
5
import kopf
5
6
import kubernetes
6
7
from kubernetes .client import ApiClient , CoreV1Api , AppsV1Api , CustomObjectsApi , V1ConfigMap , V1Service
7
8
8
9
10
+ def load_kubernetes_config ():
11
+ if 'KUBERNETES_SERVICE_HOST' in os .environ :
12
+ # We're running inside a Kubernetes cluster
13
+ return kubernetes .config .load_incluster_config ()
14
+ else :
15
+ # We're running outside the cluster
16
+ return kubernetes .config .load_kube_config ()
17
+
18
+
9
19
@kopf .on .create ('configserver' )
10
20
def create_fn (meta , spec , ** kwargs ):
11
- client = ApiClient (configuration = kubernetes . config . load_incluster_config ())
21
+ client = ApiClient (configuration = load_kubernetes_config ())
12
22
api = CoreV1Api (api_client = client )
13
23
apps_api = AppsV1Api (api_client = client )
14
24
crd_api = CustomObjectsApi (api_client = client )
@@ -100,7 +110,7 @@ def create_fn(meta, spec, **kwargs):
100
110
101
111
@kopf .on .delete ('configserver' )
102
112
def delete_fn (meta , spec , ** kwargs ):
103
- client = ApiClient (configuration = kubernetes . config . load_incluster_config ())
113
+ client = ApiClient (configuration = load_kubernetes_config ())
104
114
api = CoreV1Api (api_client = client )
105
115
apps_api = AppsV1Api (api_client = client )
106
116
@@ -122,7 +132,7 @@ def delete_fn(meta, spec, **kwargs):
122
132
123
133
124
134
def _get_config_map (config_name : str , namespace : str , logger : logging .Logger ) -> tuple [V1ConfigMap | None , CoreV1Api ]:
125
- client = kubernetes .client .api_client .ApiClient (configuration = kubernetes . config . load_incluster_config ())
135
+ client = kubernetes .client .api_client .ApiClient (configuration = load_kubernetes_config ())
126
136
api = kubernetes .client .CoreV1Api (api_client = client )
127
137
try :
128
138
config_map = api .read_namespaced_config_map (name = f"{ config_name } -values" , namespace = namespace )
0 commit comments