Skip to content

Instantly share code, notes, and snippets.

@arashilmg
Last active February 8, 2020 07:28
Show Gist options
  • Save arashilmg/c936a4e7dd7451715f5ad5f97098c029 to your computer and use it in GitHub Desktop.
Save arashilmg/c936a4e7dd7451715f5ad5f97098c029 to your computer and use it in GitHub Desktop.
Kubernetes Fuzzy Finder(fzf) helper
function kzf () { for LASTARG in $@; do :; done;
local KUBEOBJs="apiservices namespaces certificatesigningrequests networkpolicies clusterrolebindings networkpolicies clusterroles nodes componentstatuses persistentvolumeclaims configmaps persistentvolumes controllerrevisions poddisruptionbudgets cronjobs pods csidrivers podsecuritypolicies csinodes podsecuritypolicies customresourcedefinitions podtemplates daemonsets priorityclasses daemonsets replicasets deployments replicasets deployments replicationcontrollers endpoints resourcequotas eniconfigs rolebindings events roles events runtimeclasses horizontalpodautoscalers secrets ingress serviceaccounts ingresses services jobs statefulsets leases storageclasses limitranges validatingwebhookconfigurations mutatingwebhookconfigurations volumeattachments deploy csr cs cm ds deploy ep ev hpa ing limits ns no pvc pv po pdb psp rs rc quota sa svc";
if [[ $KUBEOBJs =~ (^|[[:space:]])"$LASTARG"s*($|[[:space:]]) ]] ;
then local USE=$LASTARG;
else local USE="pod";
fi;
if [[ $1 == "watch" ]];
then watch "kubectl get $USE -A | egrep -i ${@:3} 2> /dev/null || kubectl get $USE -A" ;
elif [[ $1 == "run" ]];
then local NAMESPACE=`kubectl get namespaces --no-headers |fzf --prompt="namespace: " | tr "\t" " " | tr -s " " | cut -d " " -f1`;
read -p $'What image to run:\n>' KZFIMAGE;
set -x;
kubectl -n $NAMESPACE run -it --generator=run-pod/v1 kzf-pod-run --image $KZFIMAGE sh;
{ set +x ;} 2> /dev/null ;
else echo "Searching for "$USE;
local RESOURCENAMESPACES=`kubectl get $USE -A --no-headers | fzf | tr "\t" " " | tr -s " " | cut -d " " -f1,2 | awk '{print $2, $1 }'`;
local IFS=$'\n' ;
for RESOURCENAMESPACE in $RESOURCENAMESPACES ;
do local NAMESPACE=`echo $RESOURCENAMESPACE | cut -d " " -f2`;
local RESOURCE=`kubectl get $USE -A |head -1 | egrep -i namespace 2>&1>/dev/null && echo $RESOURCENAMESPACE | cut -d " " -f1 ||echo $RESOURCENAMESPACE | cut -d " " -f2`;
set -x ;
if [[ $1 =~ (yaml|yml) ]] ;
then kubectl -o yaml get $USE $RESOURCE -n $NAMESPACE ;
elif [[ $1 =~ (bash) ]];
then kubectl exec -it $RESOURCE -n $NAMESPACE bash ;
elif [[ $1 =~ (shell|exec|sh) ]];
then kubectl exec -it $RESOURCE -n $NAMESPACE sh ;
else kubectl $@ $RESOURCE -n $NAMESPACE;
fi;
done;
{ set +x ;} 2> /dev/null ;
unset IFS ;
fi ;
}
@arashilmg
Copy link
Author

This will show all objects based on the kzf command and let you select without needing to run a kubectl get before each command to find out resource name.

requires the good old fzf package

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment