package kubectl import ( // "fmt" "strings" "errors" "os/exec" "encoding/json" log "oc-deploy/log_wrapper" ) type KubeContext struct { Bin string // Chemin vers le binaire } type kubeConfig struct { CurrentContext string `json:"current-context"` Contexts [] kubeConfigContexts `json:"contexts"` Clusters [] kubeConfigClusters `json:"clusters"` } type kubeConfigContexts struct { Name string `json:"name"` Context kubeConfigContext `json:"context"` } type kubeConfigContext struct { Cluster string `json:"cluster"` User string `json:"user"` Namespace string `json:"namespace"` } type kubeConfigCluster struct { Server string `json:"server"` } type kubeConfigClusters struct { Name string `json:"name"` Cluster kubeConfigCluster `json:"cluster"` } func (this KubeContext) GetCurrentContext() (string, error) { cmd := exec.Command(this.Bin, "config", "current-context") stdout, err := cmd.CombinedOutput() res := string(stdout) res = strings.TrimSuffix(res, "\n") return res, err } // Current Context // namespace, server func (this KubeContext) GetContext() (string, string, string, error) { cmd := exec.Command(this.Bin, "config", "view", "-o", "json") stdout, _ := cmd.CombinedOutput() var objmap kubeConfig json.Unmarshal(stdout, &objmap) currentContext := objmap.CurrentContext currentCluster := "" currentNamespace := "" for _, v := range objmap.Contexts { if v.Name == currentContext { currentNamespace = v.Context.Namespace currentCluster = v.Context.Cluster } } currentServer := "" for _, v := range objmap.Clusters { if v.Name == currentCluster { currentServer = v.Cluster.Server } } return currentContext, currentNamespace, currentServer, nil } func (this KubeContext) UseContext(newContext string) (error) { cmd := exec.Command(this.Bin, "config", "use-context", newContext) stdout, err := cmd.CombinedOutput() if err != nil { log.Log().Debug().Msg(string(stdout)) return errors.New(string(stdout)) } return nil } func (this KubeContext) Check() (error) { cmd := exec.Command(this.Bin, "cluster-info") stdout, err := cmd.CombinedOutput() if err != nil { log.Log().Debug().Msg(string(stdout)) return errors.New("Kube non disponible") } return nil }