github.com/inspektor-gadget/inspektor-gadget@v0.28.1/pkg/k8sutil/client.go (about) 1 // Copyright 2019-2021 The Inspektor Gadget authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package k8sutil 16 17 import ( 18 "errors" 19 "path/filepath" 20 21 "k8s.io/cli-runtime/pkg/genericclioptions" 22 "k8s.io/client-go/kubernetes" 23 _ "k8s.io/client-go/plugin/pkg/client/auth/oidc" 24 "k8s.io/client-go/rest" 25 "k8s.io/client-go/tools/clientcmd" 26 "k8s.io/client-go/util/homedir" 27 ) 28 29 func NewKubeConfig(kubeconfigPath string) (*rest.Config, error) { 30 var config *rest.Config 31 var err error 32 if kubeconfigPath != "" { 33 // kubeconfig is set explicitly (-kubeconfig flag or $KUBECONFIG variable) 34 config, err = clientcmd.BuildConfigFromFlags("", kubeconfigPath) 35 } else { 36 // kubeconfig from a pod Service Account token 37 config, err = rest.InClusterConfig() 38 if errors.Is(err, rest.ErrNotInCluster) { 39 // kubeconfig from $HOME/.kube/config 40 if home := homedir.HomeDir(); home != "" { 41 config, err = clientcmd.BuildConfigFromFlags("", filepath.Join(home, ".kube", "config")) 42 } 43 } 44 } 45 return config, err 46 } 47 48 func NewClientset(kubeconfigPath string) (*kubernetes.Clientset, error) { 49 config, err := NewKubeConfig(kubeconfigPath) 50 if err != nil { 51 return nil, err 52 } 53 54 apiclientset, err := kubernetes.NewForConfig(config) 55 if err != nil { 56 return nil, err 57 } 58 59 return apiclientset, nil 60 } 61 62 func NewClientsetFromConfigFlags(flags *genericclioptions.ConfigFlags) (*kubernetes.Clientset, error) { 63 config, err := flags.ToRESTConfig() 64 if err != nil { 65 return nil, err 66 } 67 68 client, err := kubernetes.NewForConfig(config) 69 if err != nil { 70 return nil, err 71 } 72 73 return client, nil 74 }