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