<p>I have the following pods,</p>
<pre><code>root@sea:scripts# kubectl get pods -l app=mubu7 -o wide
NAME     READY   STATUS    RESTARTS   AGE   IP             NODE     NOMINATED NODE   READINESS GATES
mubu71   2/2     Running   0          51m   10.244.1.215   spring   &lt;none&gt;           &lt;none&gt;
mubu72   2/2     Running   0          51m   10.244.2.17    island   &lt;none&gt;           &lt;none&gt;
</code></pre>
<p>and each one has 2 containers:</p>
<pre><code>root@sea:scripts# kubectl get pods mubu71 -o jsonpath='{.spec.containers[*].name}' | \
&gt; tr &quot; &quot; &quot;\n&quot; | uniq
mubu711
mubu712
root@sea:scripts# kubectl get pods mubu72 -o jsonpath='{.spec.containers[*].name}' | \
&gt; tr &quot; &quot; &quot;\n&quot; | uniq
mubu721
mubu722
</code></pre>
<p>I want to <strong>pass a command to both pods and all their (4) containers</strong>, but the best I can come up with is</p>
<pre><code>kubectl get pods \
-l app=mubu7 \
-o jsonpath='{.items[*].metadata.name}' | \
tr &quot; &quot; &quot;\n&quot; | uniq | \
xargs -I{} kubectl exec {} -- bash -c \
&quot;service ssh start&quot;
</code></pre>
<p>which outputs</p>
<pre><code>Defaulted container &quot;mubu711&quot; out of: mubu711, mubu712
 * Starting OpenBSD Secure Shell server sshd
   ...done.
Defaulted container &quot;mubu721&quot; out of: mubu721, mubu722
 * Starting OpenBSD Secure Shell server sshd
   ...done.
</code></pre>
<p>How can I modify the above code to <strong>run the command in all pod-containers and not just the first one</strong> or is there a preferable alternative approach?</p>
<p>Any help will be much appreciated.</p>

<p>Following code would iterate over all the pods with the label <code>app=mubu7</code>. Later it would grab their pod name and all the container's name. The list of container names is converted into an array and iterated for each pod. So it does not matter how many containers are in the pod(Eg:1,2,3..etc) this code would work.</p>
<pre><code>#JSON-path expression to extract the pod name and the list of containers
#{range .items[*]}{.metadata.name} {.spec.containers[*].name}{&quot;\n&quot;} {end}


#note that the pod name is stored in 1st variable(pod)
# container(s) name is stored in 2nd variable(containers)
kubectl get pods -l app=mubu7 -o jsonpath='{range .items[*]}{.metadata.name} {.spec.containers[*].name}{&quot;\n&quot;} {end}' |while read -r pod containers; do
     # 2nd variable consist of space seprated container lists, converting it to array
     array=($containers);
     #inner loop to iterate over containers for each pod(outer loop)
     for container in &quot;${array[@]}&quot;;do
         kubectl exec -i ${pod} -c &quot;$container&quot; &lt;/dev/null -- service ssh start
     done
done
</code></pre>
