1. 程式人生 > >使用go-template自定義kubectl get輸出

使用go-template自定義kubectl get輸出

class 模板 進行 返回結果 ces 很多 文件 pri 插入

kubectl get相關資源,默認輸出為kubectl內置,一般我們也可以使用-o json或者-o yaml查看其完整的資源信息。但是很多時候,我們需要關心的信息並不全面,因此我們需要自定義輸出的列,那麽可以使用go-template來進行實現。

go-template是golang的一種模板,可以參考template的相關說明。

比如僅僅想要查看獲取的pods中的各個pod的uid,則可以使用以下命令:

[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}}

這裏特別註意,要做一個特別的處理,就是要把{{end}}前進行換行,以便在模板中插入換行符。

當然,如果覺得這樣處理不優雅的話,也可以使用printf函數,在其中使用\n即可實現換行符的插入

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

其實有了printf,就可以很容易的實現對應字段的輸出,且樣式可以進行自己控制。比如可以這樣

[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指向該文件即可。

[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}}

使用go-template自定義kubectl get輸出