Skip to content

Instantly share code, notes, and snippets.

@realgenekim
Last active August 28, 2018 15:27
Show Gist options
  • Save realgenekim/04ee5f61753193ae7672eaa70bb280d0 to your computer and use it in GitHub Desktop.
Save realgenekim/04ee5f61753193ae7672eaa70bb280d0 to your computer and use it in GitHub Desktop.
#!/bin/bash
#
# Posting this as an example of a bash script I never should have written:
#
# it runs inside of a CI pipeline, waits for a kubernetes job to complete, looping
# until kubectl reports the job finishing, either success or fail.
#
# The problem: parsing the output frm kubectl is something I've used in a bunch of scripts,
# including exec'ing a shell, killing a pod, listing pods...
#
# So now I have repeated bash code in many shell scripts, all called by a Makefile.
#
# Parsing kubectl output should be in a function, which can be shared among multiple
# scripts/tasks.
#
# Someday, all those scripts I wrote should all be combined into one
# Planck/Lumo Clojure program.
#
# exit at first exit error (-e)
# -u: exit if you reference non-existent variable
set -eu
kubectl delete -f booktracker-job.yaml || true
kubectl create -f booktracker-job.yaml
sleep 5
# logs -f will never exit
# wait until pod is up
POD="abc"
while [[ "$POD" != "booktracker-test-job"* ]]; do
POD=`kubectl get pods| grep booktracker-test-job | sed 's/ .*//'`
echo $POD
sleep 5
done
echo Running tests in GKE: to view logs:
echo kubectl logs $POD booktracker -f
LOGGING="no"
STATE="abc"
while [ "$STATE" != "Error" ] && [ "$STATE" != "Completed" ] ; do
# returns
# NAME DESIRED SUCCESSFUL AGE
# booktracker-test 1 1 4m
# booktracker-test 1 0 15m
# kubectl get jobs
if [ "$LOGGING" == "no" ] ; then
kubectl logs $POD booktracker -f &
LOGGING="yes"
fi
OUT=`kubectl get pods -a | grep booktracker-test-job`
STATE=`echo $OUT | awk '{print $3}'`
echo $OUT
echo $STATE
# NAME READY STATUS RESTARTS AGE
# booktracker-test-9mcf6 2/2 Running 0 <invalid>
# booktracker-test-qkgbt 0/2 Error 0 15m
# booktracker-test-cpfnt 0/2 Completed 0 4m
sleep 5
done
echo "Outputting logs..."
kubectl logs $POD booktracker
case $STATE in
"Completed")
echo "Kubernetes job completed successfully!"
exit 0
;;
"Error")
echo "Kubernetes job FAIILED!!"
exit 1
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment