Shell Script to find newly added pods in kubernetes on day basics

6/19/2018

I want a shell scripts for find which kubernetes pods is newly added to the cluster. Include the pod name,date&Time and Namespace.

I have tried with the following bash script:

#!/bin/bash

p=50            #total pods count

pcount=`kubectl get pods |wc -l`

###Addition check
if [ $ncount -gt $n ]
then

    ####pods variable have all pods name.
    pods=`kubectl get pods|awk '{print $1}'|awk '{if(NR>1)print}'| xargs`

    ###start variable have all dates pods created

    start=`kubectl describe pod $pods |grep "Start Time"|awk '{print $3 $4 $5 $6}'`

    ###max variable have total number of pods
    max=`kubectl get pods |awk '{if(NR>1)print}'| wc -l`

    dt=`date +%a,%d%b%Y`

    array=( $start )

    i=0
    while [  $i -lt $max ];
    do
        #    echo "inside loop ${array[$i]}"

        if [[ "$dt" == "${array[$i]}" ]];then
             dat=`date "+%a, %d %b %Y"`
             name=`kubectl describe pod $pods |grep -v SecretName: |echo "$dat" |egrep 'Name|Start Time'`

             printf "\n"
             echo "Newly Added pods are: $name"
        fi
        i=$(( $i + 1 ))
    done
fi

The script working almost fine. But I need only today's created pods,the scripts showing all pods Name, Start Time and Namespace.

Please help.

-- Steven Lung
bash
kubernetes
linux
shell
unix

1 Answer

6/19/2018

Your script has numerous issues and inefficiencies. Repeatedly calling a somewhat heavy command like kubectl should be avoided; try to rearrange things so that you only run it once, and extract the information you need from it. I'm vaguely guessing you actually want something along the lines of

#!/bin/bash

# Store pod names in an array  
pods=($(kubectl get pods |
    awk 'NR>1 { printf sep $1; sep=" "}'))
if [ ${#pods[@]} -gt $n ]; then  # $n is still undefined!
    for pod in "${pods[@]}"; do
        kubectl describe pod "$pod" |
        awk -v dt="$(date +"%a, %d %b %Y")" '
            /SecretName:/ { next }
            /Name:/ { name=$NF }
            /Start Time:/ { t=$3 $4 $5 $6;
                if (t==dt) print name
                name="" }'
    done
fi

Once you run Awk anyway, it makes sense to refactor as much as the processing into Awk; it can do everything grep and cut and sed can do, and much more. Notice also how we use the $(command) command substitution syntax in preference over the obsolescent legacy `command` syntax.

kubectl with -o=json would probably be a lot easier and more straightforward to process programmatically so you should really look into that. I don't have a Kubernetes cluster to play around with so I'm only pointing this out as a direction for further improvement.

-- tripleee
Source: StackOverflow