kubectl使用命令行插件

发布时间 2023-10-17 16:28:19作者: 小糊涂90

为了扩展kubectl的功能,Kubernetes从1.8版本开始引入插件机制,在1.14版本时达到稳定版。
用户自定义插件的可执行文件名需要以“kubectl-”开头,复制到$PATH中的某个目录(如/usr/local/bin)下,然后就可以通过kubectl 运行自定义插件了。
例如,通过Shell脚本实现一个名为hello的插件,其功能为在屏幕上输出字符串“hello world”。创建名为“kubectl-hello”的Shell脚本文件,内容如下:

[root@k8s-master ~]# vi kubectl-hello
#!/bin/bash
echo "this is tanlaing"

[root@k8s-master ~]# chmod +x kubectl-hello

[root@k8s-master ~]# mv kubectl-hello /usr/local/bin/
      
[root@k8s-master ~]# kubectl hello
this is tanlaing
       
[root@k8s-master ~]# kubectl plugin list
The following compatible plugins are available:
/usr/local/bin/kubectl-hello

卸载插件也很简单,只需要删除插件文件即可

通过插件机制,可以将某些复杂的kubectl命令简化为运行插件的方式。例如想创建一个命令来查看当前上下文环境(context)中的用户名,则可以通过kubectl config view命令进行查看。为此,可以创建一个名为“kubectl-whoami”的Shell脚本,内容如下:

kubectl config view --template='{{ range .contexts }}{{if eq .name "'$(kubectl config current-context)'"}}Current user: {{ printf "%s\n" .context.user }}{{end}}{{end}}'
[root@k8s-master ~]# mv kubectl-whoami  /usr/local/bin/
[root@k8s-master ~]# chmod +x /usr/local/bin/kubectl-whoami 
[root@k8s-master ~]# kubectl-whoami 
Current user: kubernetes-admin
[root@k8s-master ~]# kubectl whoami 
Current user: kubernetes-admin