使用go-template自定义kubectl get输出

kubectl get相关资源,默认输出为kubectl内置,通常咱们也可使用-o json或者-o yaml查看其完整的资源信息。可是不少时候,咱们须要关心的信息并不全面,所以咱们须要自定义输出的列,那么可使用go-template来进行实现。node

go-template是golang的一种模板,能够参考template的相关说明nginx

好比仅仅想要查看获取的pods中的各个pod的uid,则可使用如下命令:golang

[root@node root]# kubectl get pods --all-namespaces -o go-template --template='{{range .items}}{{.metadata.uid}}
{{end}}'
0313ffff-f1f4-11e7-9cda-40f2e9b98448
ee49bdcd-f1f2-11e7-9cda-40f2e9b98448
f1e0eb80-f1f2-11e7-9cda-40f2e9b98448
[root@node-106 xuxinkun]# kubectl get pods -o yaml 
apiVersion: v1
items:
- apiVersion: v1
  kind: Pod
  metadata:
    name: nginx-deployment-1751389443-26gbm
    namespace: default
    uid: a911e34b-f445-11e7-9cda-40f2e9b98448
  ...
- apiVersion: v1
  kind: Pod
  metadata:
    name: nginx-deployment-1751389443-rsbkc
    namespace: default
    uid: a911d2d2-f445-11e7-9cda-40f2e9b98448
  ...
- apiVersion: v1
  kind: Pod
  metadata:
    name: nginx-deployment-1751389443-sdbkx
    namespace: default
    uid: a911da1a-f445-11e7-9cda-40f2e9b98448
    ...
kind: List
metadata: {}
resourceVersion: ""

由于get pods的返回结果是List类型,获取的pods都在items这个的value中,所以须要遍历items,也就有了{{range .items}}。然后经过模板选定须要展现的内容,就是items中的每一个{{.metadata.uid}}json

这里特别注意,要作一个特别的处理,就是要把{{end}}前进行换行,以便在模板中插入换行符。api

固然,若是以为这样处理不优雅的话,也可使用printf函数,在其中使用\n便可实现换行符的插入函数

[root@node root]# kubectl get pods --all-namespaces -o go-template --template='{{range .items}}{{printf "%s\n" .metadata.uid}}{{end}}'

其实有了printf,就能够很容易的实现对应字段的输出,且样式能够进行本身控制。好比能够这样ui

[root@node root]# kubectl get pods --all-namespaces -o go-template --template='{{range .items}}{{printf "|%-20s|%-50s|%-30s|\n" .metadata.namespace .metadata.name .metadata.uid}}{{end}}'
|console             |console-4d2d7eab-1377218307-7lg5v                 |0313ffff-f1f4-11e7-9cda-40f2e9b98448|
|console             |console-4d2d7eab-1377218307-q3bjd                 |ee49bdcd-f1f2-11e7-9cda-40f2e9b98448|
|cxftest             |ipreserve-f15257ec-3788284754-nmp3x               |f1e0eb80-f1f2-11e7-9cda-40f2e9b98448|

除了使用go-template以外,还可使用go-template-file。则模板不用经过参数传进去,而是写成一个文件,而后须要指定template指向该文件便可。spa

[root@node root]#  kubectl get pods --all-namespaces -o go-template-file --template=/home/template_file
[root@node root]# cat /home/template_file
{{range .items}}{{printf "%s\n" .metadata.uid}}{{end}}
相关文章
相关标签/搜索