Skip to content

Instantly share code, notes, and snippets.

@leoh0
Last active September 18, 2019 09:17
Show Gist options
  • Save leoh0/8371eac0bc6d8d02a681acd8617aef3f to your computer and use it in GitHub Desktop.
Save leoh0/8371eac0bc6d8d02a681acd8617aef3f to your computer and use it in GitHub Desktop.
k8s get multi shell & get multiple pods logs based on its label
# NOTE: Please install kubectl, fzf, stern, tmux first before using this functions
# NOTE: 사용전에 kubectl, fzf, stern, tmux 를 먼저 설치하세요.
# Choose multiple pods using `TAB` and then get their shells using `ENTER`.
# TAB으로 pod들을 선택하고 ENTER로 그 pod들의 shell을 동시에 얻습니다.
function multi_login() {
pods=$(kubectl get pods --all-namespaces | sed '1d' | fzf -x -m -e +s --reverse --bind=left:page-up,right:page-down --no-mouse | awk '{print $1","$2}')
if [[ $pods != "" ]]; then
init="true"
tmuxname=k8s-ns-$(date +%s)
tmux kill-session -t "$tmuxname" > /dev/null 2> /dev/null || true
while read -r line ;do
NS=$(echo "$line" | cut -d',' -f1)
NAME=$(echo "$line" | cut -d',' -f2)
connect="kubectl exec -ti $NAME -n $NS -- bash || kubectl exec -ti $NAME -n $NS -- sh "
if [ "${init}" == "true" ]; then
tmux new-session -d -s "$tmuxname" "export KUBECONFIG=${KUBECONFIG}; $connect"
if (( $(tmux ls 2> /dev/null | grep -c "${tmuxname}") > 0 )) ; then
init="false"
fi
else
tmux split-window -t "${tmuxname}" "export KUBECONFIG=${KUBECONFIG}; ${connect}" && \
tmux select-layout -t "${tmuxname}" "tiled"
fi
done <<< "$pods"
tmux set-window-option -t "${tmuxname}" synchronize-panes on
tmux send-keys -t 0 "export TERM=xterm-color ; shopt -s checkwinsize; printf '\\e[8;320;320t' ; clear; tput cols" C-m
tmux -2 a -t "$tmuxname"
fi
}
# Select a pod using `ENTER` then get logs from pods same as their labels.
# `ENTER`로 pod을 선택하면 동일한 라벨을 같은 팟들의 로그를 동시에 볼 수 있습니다.
function label_log() {
pods=$(kubectl get pods --all-namespaces \
--no-headers --show-labels | \
sed '1d' | \
fzf -x -m -e +s --reverse --no-mouse \
--bind=left:page-up,right:page-down | \
awk '{print $1" "$7}');
if [[ $pods != "" ]]; then
namespace=${pods/ *};
label=${pods/* };
stern -t -n "$namespace" -l "$label";
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment