1
1
const path = require ( 'path' ) ;
2
+ const fs = require ( 'fs' ) ;
2
3
const { KubeConfig, Client } = require ( 'kubernetes-client' ) ;
3
4
const Request = require ( 'kubernetes-client/backends/request' ) ;
4
5
const _ = require ( 'lodash' ) ;
6
+ const { homedir } = require ( 'os' ) ;
7
+
8
+ const _getKubeConfig = ( kubeconfigPath ) => {
9
+ const kc = new KubeConfig ( ) ;
10
+ const kubePath = kubeconfigPath || process . env . KUBECONFIG || path . join ( homedir ( ) , '.kube' , 'config' ) ;
11
+ if ( fs . existsSync ( kubePath ) ) {
12
+ kc . loadFromFile ( kubePath ) ;
13
+ } else {
14
+ kc . loadFromCluster ( ) ;
15
+ }
16
+
17
+ return kc ;
18
+ }
5
19
6
20
const getKubeContext = ( kubeconfigPath ) => {
7
- // eslint-disable-next-line global-require
8
- const homedir = require ( 'os' ) . homedir ( ) ;
9
- const kubePath = kubeconfigPath || process . env . KUBECONFIG || path . join ( homedir , '.kube' , 'config' ) ;
10
- const kubeconfig = new KubeConfig ( ) ;
11
- kubeconfig . loadFromFile ( kubePath ) ;
21
+ const kubeconfig = _getKubeConfig ( kubeconfigPath ) ;
12
22
return kubeconfig . currentContext ;
13
23
} ;
14
24
const getAllKubeContexts = ( kubeconfigPath ) => {
15
- // eslint-disable-next-line global-require
16
- const homedir = require ( 'os' ) . homedir ( ) ;
17
- const kubePath = kubeconfigPath || process . env . KUBECONFIG || path . join ( homedir , '.kube' , 'config' ) ;
18
- const kubeconfig = new KubeConfig ( ) ;
19
- kubeconfig . loadFromFile ( kubePath ) ;
25
+ const kubeconfig = _getKubeConfig ( kubeconfigPath ) ;
20
26
const { contexts } = kubeconfig ;
21
27
if ( contexts ) {
22
28
return contexts . reduce ( ( acc , curr ) => {
@@ -26,11 +32,7 @@ const getAllKubeContexts = (kubeconfigPath) => {
26
32
}
27
33
} ;
28
34
const getAllNamespaces = async ( kubeconfigPath , kubeContextName ) => {
29
- // eslint-disable-next-line global-require
30
- const homedir = require ( 'os' ) . homedir ( ) ;
31
- const kubePath = kubeconfigPath || process . env . KUBECONFIG || path . join ( homedir , '.kube' , 'config' ) ;
32
- const kubeconfig = new KubeConfig ( ) ;
33
- kubeconfig . loadFromFile ( kubePath ) ;
35
+ const kubeconfig = _getKubeConfig ( kubeconfigPath ) ;
34
36
kubeconfig . setCurrentContext ( kubeContextName ) ;
35
37
const backend = new Request ( { kubeconfig } ) ;
36
38
const client = new Client ( { backend, version : 1.13 } ) ;
0 commit comments