Skip to content

Instantly share code, notes, and snippets.

@surfsoft
Created April 15, 2021 11:26
Show Gist options
  • Select an option

  • Save surfsoft/f41025d105d7233ebd1be7f6e130d323 to your computer and use it in GitHub Desktop.

Select an option

Save surfsoft/f41025d105d7233ebd1be7f6e130d323 to your computer and use it in GitHub Desktop.
Kubernetes productivity scripts (WIP)
#! /bin/bash
# A set of bash functions that provide simplified commands to perform common kubernetes functions
# Set the default context.
# $1 = some unique portion of the context you want.
# Will list matching contexts if $1 is not unique.
function set-context() {
MATCHES=$(kubectl config get-contexts | awk '{ print $1 }' | grep "$1" | wc -l)
if test $((MATCHES)) -eq 1 ; then
TARGET=$(kubectl config get-contexts | awk '{ print $1 }' | grep "$1")
echo "Setting context to $TARGET"
kubectl config use-context $TARGET
elif test $((MATCHES)) -eq 0 ; then
echo "No contexts match '$1'"
else
echo "Multiple contexts match '$1' - be more specific:"
kubectl config get-contexts | awk '{ print $1 }' | grep "$1"
fi
}
# Set the default namespace.
# $1 = some unique portion of the namespace you want.
# Will list matching namespaces if $1 is not unique.
function set-namespace() {
MATCHES=$(kubectl get namespaces | awk '{ print $1 }' | grep "$1" | wc -l)
if test $((MATCHES)) -eq 1 ; then
TARGET=$(kubectl get namespaces | awk '{ print $1 }' | grep "$1")
echo "Setting namespace to $TARGET"
kubectl config set-context --current --namespace=$TARGET
elif test $((MATCHES)) -eq 0 ; then
echo "No namespaces match '$1'"
else
echo "Multiple namespaces match '$1' - be more specific:"
kubectl config get-contexts | awk '{ print $1 }' | grep "$1"
fi
}
# Start a bash script in the pod of your choice
# $1 = some unique portion of the pod name. Can be omitted if there is only one pod in the namespace.
# Will list matching pods if $1 is not unique.
# Requires that bash is available and enabled to run in the pod.
function podbash() {
MATCHES=$(kubectl get pods | awk '{ print $1 }' | grep -v NAME | grep "$1" | wc -l)
if test $((MATCHES)) -eq 1 ; then
TARGET=$(kubectl get pods | awk '{ print $1 }' | grep -v NAME | grep "$1")
echo "Starting bash in $TARGET"
kubectl exec -ti "$TARGET" -- bash
elif test $((MATCHES)) -eq 0 ; then
echo "No pods match '$1'"
else
echo "Multiple pods match '$1' - be more specific:"
kubectl get pods | awk '{ print $1 }' | grep -v NAME | grep "$1"
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment