bashkubernetesyamlwc

how to count num of containers crreated in 1 yaml file with 1 liner cmd in bash?


There is k8s pod yaml file that has 3 containers, here is the part of the yaml file:

Containers:
  apple:
    Container ID:  
    Image:         busybox
    Image ID:      
    Port:          <none>
    Host Port:     <none>
    Command:
      sleep
      4500
    State:          Waiting
      Reason:       ContainerCreating
    Ready:          False
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-2ccr2 (ro)
  wine:
    Container ID:  
    Image:         busybox
    Image ID:      
    Port:          <none>
    Host Port:     <none>
    Command:
      sleep
      4500
    State:          Waiting
      Reason:       ContainerCreating
    Ready:          False
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-2ccr2 (ro)
  scarlet:
    Container ID:  
    Image:         busybox
    Image ID:      
    Port:          <none>
    Host Port:     <none>
    Command:
      sleep
      4500
    State:          Waiting
      Reason:       ContainerCreating
    Ready:          False
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-2ccr2 (ro)

I did "kubectl describe pod mypod"

I still had to count the num of containers. What should i add to get the num of containers out of the file? Like this:

kubectl describe pod mypod | grep -i containers

But this only finds the keyword.

kubectl describe pod mypod | grep -i containers | wc -l

I just want it a nice eloquent 1 liner cmd to show me num of containers.


Solution

  • You can use grep for counting the occurrences of a key that every container is bound to have once and that cannot be mistaken with an other key; for example Container ID::

    kubectl describe pod mypod | grep -c 'Container ID:'