client-go是用于在Kubernetes中运行apply命令的库。

huangapple go评论80阅读模式
英文:

client-go for Kubernetes run apply commands

问题

你可以使用client-go库在Go语言中运行kubectl apply命令。以下是一个示例代码:

package main

import (
	"flag"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"

	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/serializer"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/clientcmd"
	"k8s.io/client-go/util/homedir"
)

func main() {
	// 设置kubeconfig文件路径,如果未设置则使用默认路径
	var kubeconfig *string
	if home := homedir.HomeDir(); home != "" {
		kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
	} else {
		kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
	}
	flag.Parse()

	// 使用kubeconfig文件创建一个rest.Config对象
	config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
	if err != nil {
		panic(err.Error())
	}

	// 创建一个新的Kubernetes客户端
	clientset, err := kubernetes.NewForConfig(config)
	if err != nil {
		panic(err.Error())
	}

	// 读取crds.yaml文件内容
	filePath := "path/to/crds.yaml"
	data, err := ioutil.ReadFile(filePath)
	if err != nil {
		panic(err.Error())
	}

	// 将文件内容解析为Unstructured对象
	decode := serializer.NewCodecFactory(runtime.NewScheme()).UniversalDeserializer().Decode
	obj, _, err := decode(data, nil, nil)
	if err != nil {
		panic(err.Error())
	}
	unstructuredObj := obj.(*unstructured.Unstructured)

	// 使用client-go的Apply方法将Unstructured对象应用到集群中
	_, err = clientset.
		Dynamic().
		Resource(unstructuredObj.GetKind()).
		Namespace(unstructuredObj.GetNamespace()).
		Create(unstructuredObj, metav1.CreateOptions{})
	if err != nil {
		panic(err.Error())
	}

	fmt.Println("CRD applied successfully!")
}

请将代码中的path/to/crds.yaml替换为你的crds.yaml文件的实际路径。这段代码将读取crds.yaml文件的内容,并使用client-go的Apply方法将其应用到Kubernetes集群中。

英文:

How can I run kubectl apply commands from go via client-go?
e.g.:
I'm having a file called crds.yaml and I want to run it via client-go

I can't find any examples about how to do so can someone please help?

答案1

得分: 2

你需要解码你的 .yaml 文件。这里是完整的答案(包含代码示例)。

英文:

You need to decode your .yaml file

Here it's the complete answer (with code example)

答案2

得分: 1

根据您提供的链接,我对这种类型的调用进行了翻译:

yamlFile, err := ioutil.ReadFile("custom.yaml")
if err != nil {
    log.Printf("yamlFile.Get err #%v ", err)
}

var ctx context.Context
var c client.Client
var actionFn ForEachObjectInYAMLActionFunc

err = ForEachObjectInYAML(ctx, c, yamlFile, "default", actionFn)
if err != nil {
    fmt.Println(err)
}

但是它失败了,显示以下错误信息:

panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x10ac5cc]

goroutine 1 [running]:
main.ForEachObjectInYAML({0x0, 0x0}, {0x0, 0x0}, {0xc000880000?, 0xc0000021a0?, 0x200000003?}, {0x12bf20f, 0x7}, 0x0)
       apply.go:125 +0x12c
main.main()
       apply.go:34 +0xc5
exit status 2

还有以下代码片段:

if err := actionFn(ctx, c, obj); err != nil {
    return err
}

请问我做错了什么?

英文:

I ended up having this type of call based on what is on the link you provided

	yamlFile, err := ioutil.ReadFile("custom.yaml")
if err != nil {
log.Printf("yamlFile.Get err   #%v ", err)
}
var ctx context.Context
var c client.Client
var actionFn ForEachObjectInYAMLActionFunc
err = ForEachObjectInYAML(ctx, c, yamlFile, "default", actionFn)
if err != nil {
fmt.Println(err)
}

But it is failing with

panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x10ac5cc]
goroutine 1 [running]:
main.ForEachObjectInYAML({0x0, 0x0}, {0x0, 0x0}, {0xc000880000?, 0xc0000021a0?, 0x200000003?}, {0x12bf20f, 0x7}, 0x0)
apply.go:125 +0x12c
main.main()
apply.go:34 +0xc5
exit status 2

And there is:

if err := actionFn(ctx, c, obj); err != nil {
return err
}

Any idea what I'm doing wrong?

huangapple
  • 本文由 发表于 2022年11月25日 21:53:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/74573857.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定