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 KubectlCommand) GetCurrentContext() (string, error) { bin := this.Bin msg := fmt.Sprintf("%s get config current-context", bin) log.Log().Debug().Msg(msg) cmd_args := strings.Split(msg, " ") cmd := this.Exec(cmd_args[0], cmd_args[1:]...) stdout, err := cmd.CombinedOutput() res := string(stdout) res = strings.TrimSuffix(res, "\n") return res, err } // Current Context // namespace, server func (this KubectlCommand) GetContext() (string, string, string, error) { bin := this.Bin msg := fmt.Sprintf("%s config view -o json", bin) log.Log().Debug().Msg(msg) cmd_args := strings.Split(msg, " ") cmd := this.Exec(cmd_args[0], cmd_args[1:]...) stdout, err := cmd.CombinedOutput() if err != nil { return "", "", "", errors.New(string(stdout)) } var objmap kubeConfig err = json.Unmarshal(stdout, &objmap) if err != nil { return "", "", "", err } 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 KubectlCommand) 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 KubectlCommand) Check() (error) { bin := this.Bin msg := fmt.Sprintf("%s cluster-info", bin) log.Log().Debug().Msg(msg) cmd_args := strings.Split(msg, " ") cmd := this.Exec(cmd_args[0], cmd_args[1:]...) stdout, err := cmd.CombinedOutput() if err != nil { log.Log().Debug().Msg(string(stdout)) return errors.New("Kube non disponible") } return nil }