<p>How can I use the <code>--output=custom-columns</code> option for the the Kubernetes CLI (<code>kubectl</code>) to select array elements?</p>
<p>In other words, how can I turn this:</p>
<pre class="lang-shell prettyprint-override"><code>kubectl get services

#=&gt;

NAME            TYPE       CLUSTER-IP     EXTERNAL-IP      PORT(S)          AGE
kafka-manager   NodePort   10.3.242.200   146.148.20.235   9000:32619/TCP   0d
spark-master    NodePort   10.3.242.209   104.199.21.235   9000:32619/TCP   0d
</code></pre>
<p>into this?</p>
<pre class="lang-shell prettyprint-override"><code>kubectl get services \
--output=custom-columns=. . .

#=&gt;

NAME            EXTERNAL-ENDPOINT     
kafka-manager   146.148.20.225:9000
spark-master    104.199.21.225:7077
</code></pre>
<p>What I have so far:</p>
<pre class="lang-shell prettyprint-override"><code>kubectl get services \
--output=custom-columns='NAME:.metadata.name,IP:.spec.clusterIP,PORT:.spec.ports'

#=&gt;

NAME            IP             PORT
kafka-manager   10.3.242.200   [map[nodePort:32619 port:9000 protocol:TCP targetPort:9000]]
spark-master    10.3.242.209   [map[nodePort:30588 port:7077 protocol:TCP targetPort:7077]]
</code></pre>

nik
<p><strong>TLDR</strong></p>
<p>For an element that is in a list use <code>*</code> in square brackets.</p>
<p>So your query should look like this:</p>
<pre class="lang-shell prettyprint-override"><code>kubectl get service \
-n kube-system \
-o=custom-columns='NAME:.metadata.name,IP:.spec.clusterIP,PORT:.spec.ports[*].targetPort'

#=&gt;

NAME                   IP           PORT
kube-dns               10.0.0.10    53,53
kubernetes-dashboard   10.0.0.250   9090
</code></pre>
<p>Notice the <code>*</code> in <code>PORT:.spec.ports[*].targetPort</code>.</p>
<p><strong>Details:</strong></p>
<p>So <code>kubectl</code> is expecting a <code>json-path-expr</code> after <code>header</code>. The error I got when playing with expressions was following:</p>
<pre class="lang-shell prettyprint-override"><code>expected &lt;header&gt;:&lt;json-path-expr&gt;
</code></pre>
<p>To iterate over all elements in a list instead of putting an index just use <code>*</code>.</p>
<p>Various other json-path expressions can be found <a href="http://goessner.net/articles/JsonPath" rel="noreferrer">here</a>.</p>
