1 概述:

1.1 环境

版本信息如下:
a、操作系统:centos 7.6,amd64
b、kubernetes版本:v1.15.0
c、docker版本:v1.18.06
d、golang版本: v1.13

2 代码:

指定多个目录或文件,效果等同于kubectl apply。

package main

import (
	"k8s.io/cli-runtime/pkg/genericclioptions"
	"k8s.io/cli-runtime/pkg/printers"
	cliresource "k8s.io/cli-runtime/pkg/resource"
	"k8s.io/kubectl/pkg/cmd/apply"
	"k8s.io/kubectl/pkg/cmd/delete"
	"log"
	"os"
)

func main() {

	var (
		kubeConfigFile string = os.Getenv("HOME") + "/.kube/config"
		err            error
	)
	kubeConfigFlags := genericclioptions.NewConfigFlags(true).WithDeprecatedPasswordFlag()
	kubeConfigFlags.KubeConfig = &kubeConfigFile

	builder := cliresource.NewBuilder(kubeConfigFlags)
	if err != nil {
		log.Println(err)
		return
	}
	ioStreams := genericclioptions.IOStreams{In: os.Stdin, Out: os.Stdout, ErrOut: os.Stderr}
	o := apply.NewApplyOptions(ioStreams)
	// default namespace for k8s resource
	o.Namespace = "default"
	o.Builder = builder
	o.DeleteOptions = &delete.DeleteOptions{
		FilenameOptions: cliresource.FilenameOptions{
			// target k8s yaml files and directories that contain k8s yaml files
			// 指定目标k8s文件和目录
			Filenames:[]string{"/opt"},
			
			Recursive: false,
		},
	}
	o.ToPrinter = func(operation string) (printers.ResourcePrinter, error) {
		o.PrintFlags.NamePrintFlags.Operation = operation
		return o.PrintFlags.ToPrinter()
	}


	err = o.Run()
	if err != err {
		log.Println(err)
	}
}
Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐