Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kubernetes custom-columns select element from array

I try to write a template, to list the names of my services as well as their external endpoints + ports. However, I don't find any examples or documentation how to select an element from an array, in this case port from the ports array.

I got that far:

 kubectl get service -o=custom-columns=NAME:.metadata.name,IP:.spec.clusterIP,PORT:.spec.ports

To give a more concrete example, this are my running services:

NAME                  CLUSTER-IP     EXTERNAL-IP      PORT(S)                               AGE
kafka-manager         10.3.242.200   146.148.20.235   9000:32619/TCP                        11h
spark-master          10.3.242.209   104.199.21.235   7077:30588/TCP                        11h

I wish to get:

NAME                  EXTERNAL-ENDPOINT     
kafka-manager         146.148.20.225:9000
spark-master          104.199.21.225:7077
like image 397
nik Avatar asked Apr 05 '17 08:04

nik


2 Answers

TLDR

for an element that is list use * in square bracket.

So your query should look like this:

$ kubectl get service -n kube-system  -o=custom-columns=NAME:.metadata.name,IP:.spec.clusterIP,PORT:.spec.ports[*].targetPort
NAME                   IP           PORT
kube-dns               10.0.0.10    53,53
kubernetes-dashboard   10.0.0.250   9090

Notice the * in PORT:.spec.ports[*].targetPort.

Details:

So kubernetes is expecting a json-path-expr after header. The error I got when playing with expressions was following:

expected <header>:<json-path-expr>

So to iterate over all elements in a list instead of putting an index just use *.

Various other json-path expressions can be found here.

like image 133
surajd Avatar answered Oct 14 '22 03:10

surajd


You can use * for understanding which data in the json. For example:

kubectl get svc gdpr -o custom-columns=svc:*

As for me kubectl get svc -o custom-columns=svc:.metadata.name,IP:.metadata.annotations.domainName,PORT:.spec.ports[*].targetPort was perfect (due external IP info) and looks like:

event   site1.com 9000 
gdpr    site2.com 3333,8080
svcInt  none      80
ui      site6.com 80,6123,6124,6125,8081

p.s. About list external IP and hosts:

kubectl get nodes -o jsonpath='{range .items[*]}{.metadata.name} {.status.addresses[?(@.type=="ExternalIP")].address}{"\n"}'
ip-10-10-40-13.xxxxx.internal xx.xx.xx.175
ip-10-10-40-15.xxxxx.internal xx.xx.xx.236
ip-10-10-40-18.xxxxx.internal xx.xx.xx.207

kubectl get nodes -o jsonpath='{range .items[*]}{.status.addresses[?(@.type=="ExternalIP")].address}{"\n"}'
xx.xx.xx.175
xx.xx.xx.236
xx.xx.xx.207
like image 45
dmitry_podyachev Avatar answered Oct 14 '22 04:10

dmitry_podyachev