kubectl插件之pod通过标签过滤
package mainimport ("context""fmt""github.com/olekukonko/tablewriter""github.com/spf13/cobra"v1 "k8s.io/apimachinery/pkg/apis/meta/v1""k8s.io/cli-runtime/pkg/genericclioptions""k8s.io/client-go/kubern
·
package main
import (
"context"
"fmt"
"github.com/olekukonko/tablewriter"
"github.com/spf13/cobra"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/cli-runtime/pkg/genericclioptions"
"k8s.io/client-go/kubernetes"
"log"
"os"
)
var (
Fields string
Labels string
ShowLabels bool
cfgFlags *genericclioptions.ConfigFlags
client=InitClient()
)
func InitClient() *kubernetes.Clientset{
cfgFlags =genericclioptions.NewConfigFlags(true)
config,err:= cfgFlags.ToRawKubeConfigLoader().ClientConfig()
if err!=nil{log.Fatalln(err)}
c,err:=kubernetes.NewForConfig(config)
if err!=nil{log.Fatalln(err)}
return c
}
func MergeFlags(cmd *cobra.Command){
cfgFlags.AddFlags(cmd.Flags())
}
func RunCmd(f func(c *cobra.Command, args []string) error ) {
cmd := &cobra.Command{
Use: "kubectl pods [flags]",
Short: "list pods ",
Example: "kubectl pods [flags]",
SilenceUsage: true,
RunE:f,
}
MergeFlags(cmd)
//用来支持 是否 显示标签
cmd.Flags().BoolVar(&ShowLabels,"show-labels",false,"kubectl pods --show-lables")
cmd.Flags().StringVar(&Labels,"labels","","kubectl pods --lables app=ngx or kubectl pods --lables=\"app=ngx,version=v1\"")
cmd.Flags().StringVar(&Fields,"fields","","kubectl pods --fields=\"status.phase=Running\"")
err:=cmd.Execute()
if err!=nil{
log.Fatalln(err)
}
}
func Map2String(m map[string]string) (ret string ) {
for k,v:=range m{
ret+=fmt.Sprintf("%s=%s\n",k,v)
}
return
}
//初始化头
func InitHeader(table *tablewriter.Table) []string {
commonHeaders:=[]string{"名称", "命名空间", "IP","状态"}
if ShowLabels{
commonHeaders=append(commonHeaders,"标签")
}
return commonHeaders
}
func run(c *cobra.Command, args []string) error {
ns,err:=c.Flags().GetString("namespace")
if err!=nil{return err}
if ns==""{ns="default"}
list,err:=client.CoreV1().Pods(ns).List(context.Background(), v1.ListOptions{LabelSelector: Labels, FieldSelector: Fields,})
if err!=nil{return err}
table := tablewriter.NewWriter(os.Stdout)
//设置头
table.SetHeader(InitHeader(table))
for _,pod:=range list.Items {
podRow:=[]string{pod.Name,pod.Namespace,pod.Status.PodIP,
string(pod.Status.Phase)}
if ShowLabels{
podRow=append(podRow,Map2String(pod.Labels))
}
table.Append(podRow)
}
table.SetAutoWrapText(false)
table.SetAutoFormatHeaders(true)
table.SetHeaderAlignment(tablewriter.ALIGN_LEFT)
table.SetAlignment(tablewriter.ALIGN_LEFT)
table.SetCenterSeparator("")
table.SetColumnSeparator("")
table.SetRowSeparator("")
table.SetHeaderLine(false)
table.SetBorder(false)
table.SetTablePadding("\t") // pad with tabs
table.SetNoWhiteSpace(true)
table.Render()
return nil
}
func main() {
RunCmd(run)
}
更多推荐
已为社区贡献44条内容
所有评论(0)