A while ago, I was asked to capture a LOT of data for a support case, where they wanted lots of commands to be run, like “kubectl get namespace” and then for each namespace, get all the pods with “kubectl get pods -n $namespace” and then describe each pod with “kubectl get pod -n namespace $podname”. Then do the same with all the services, deployments, ingresses and endpoints.
I wrote this function, and a supporting script to execute the actual checks, and just found it while clearing up!
#!/bin/bash
filename="$(echo $* | sed -E -e 's~[ -/\\]~_~g').log"
echo "\$ $@" | tee "${filename}"
$@ 2>&1 | tee -a "${filename}"
This script is quite simple, it does three things
- Take the command you’re about to run, strip all the non-acceptable-filename characters out and replace them with underscores, and turn that into the output filename.
- Write the command into the output file, replacing any prior versions of that file
- Execute the command, and append the log to the output file.
So, how do you use this? Simple
log_result my-command --with --all --the options
This will produce a file called my-command_--with_--all_--the_options.log
that contains this content:
$ my-command --with --all --the options
Congratulations, you ran my-command and turned on the options "--with --all --the options". Nice one!
… oh, and the command I ran to capture the data for the support case?
log_result kubectl get namespace
for TYPE in pod ingress service deployment endpoints
do
for ns in $(kubectl get namespace | grep -v NAME | awk '{print $1}' )
do
echo $ns
for item in $(kubectl get $TYPE -n $ns | grep -v NAME | awk '{print $1}')
do
log_result kubectl get $TYPE -n $ns $item -o yaml
log_result kubectl describe $TYPE -n $ns $item
done
done
done
Featured image is “Travel log texture” by “Mary Vican” on Flickr and is released under a CC-BY license.