代码拉取完成,页面将自动刷新
package kubectl
import (
"io/ioutil"
"os"
"os/exec"
"strings"
"k8s.io/client-go/tools/clientcmd"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
)
const (
tmpDir = "./management-state/tmp"
)
func Apply(yaml []byte, kubeConfig *clientcmdapi.Config) ([]byte, error) {
kubeConfigFile, err := tempFile("kubeconfig-")
if err != nil {
return nil, err
}
defer os.Remove(kubeConfigFile.Name())
yamlFile, err := tempFile("yaml-")
if err != nil {
return nil, err
}
defer os.Remove(yamlFile.Name())
if err := ioutil.WriteFile(yamlFile.Name(), yaml, 0600); err != nil {
return nil, err
}
if err := clientcmd.WriteToFile(*kubeConfig, kubeConfigFile.Name()); err != nil {
return nil, err
}
cmd := exec.Command("kubectl",
"--kubeconfig",
kubeConfigFile.Name(),
"apply",
"-f",
yamlFile.Name())
return runWithHTTP2(cmd)
}
func tempFile(prefix string) (*os.File, error) {
if _, err := os.Stat(tmpDir); os.IsNotExist(err) {
if err = os.MkdirAll(tmpDir, 0755); err != nil {
return nil, err
}
}
f, err := ioutil.TempFile(tmpDir, prefix)
if err != nil {
return nil, err
}
return f, f.Close()
}
func ApplyWithNamespace(yaml []byte, namespace string, kubeConfig *clientcmdapi.Config) ([]byte, error) {
kubeConfigFile, err := tempFile("kubeconfig-")
if err != nil {
return nil, err
}
defer os.Remove(kubeConfigFile.Name())
yamlFile, err := tempFile("yaml-")
if err != nil {
return nil, err
}
defer os.Remove(yamlFile.Name())
if err := ioutil.WriteFile(yamlFile.Name(), yaml, 0600); err != nil {
return nil, err
}
if err := clientcmd.WriteToFile(*kubeConfig, kubeConfigFile.Name()); err != nil {
return nil, err
}
cmd := exec.Command("kubectl",
"--kubeconfig",
kubeConfigFile.Name(),
"-n",
namespace,
"apply",
"-f",
yamlFile.Name())
return runWithHTTP2(cmd)
}
func runWithHTTP2(cmd *exec.Cmd) ([]byte, error) {
var newEnv []string
for _, env := range os.Environ() {
if strings.HasPrefix(env, "DISABLE_HTTP2") {
continue
}
newEnv = append(newEnv, env)
}
cmd.Env = newEnv
return cmd.CombinedOutput()
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。