2019年6月28日金曜日

kubectl コマンド実行時に対象となるクラスターを表示し、実行を保留して誤爆を防ぐ kubectl ラッパーを書いた

kubectl コマンドで破壊的オペレーションを実行する際、実行時の current-context を出力することで、ユーザーに実行対象の Kubernetes クラスターを確認させ、かつユーザーの入力があるまで実行を保留し誤爆を防いでくれるやつです。

# Run the `source` command to load this file into the current shell like follow:
#   $ source kubectl-wrapper.sh

# kubect-wrapper displays the current-context and prompts for user confirmation
# when trying to execute kubectl's subcommands that can update the cluster's state.
kubectl() { (
  # if has 1 argument || has -h --help --dry-run option || Sub-commands that are not dangerous if executed without confirmation; then
  if [ $# -le 1 ] || { echo " $* " | grep -Eq -- ' -h | --help | --dry-run '; } \
    || { echo " $* " | grep -Eq ' api-resources | api-version | cluster-info | completion | config | describe | diff | explain | get | logs | top | version | wait '; }; then
    command kubectl "$@"
    return $?
  fi
  printf "\e[01;33m%s\n%s\e[0m" "# CurrentContext: " "#   "
  command kubectl config current-context
  printf "\e[01;33m%s\e[0m" "# Press Enter key to continue... "
  read -r
  command kubectl "$@"
)}

GKE に限らずですが、複数の k8s クラスターを使い分けてると、 context を誤爆しそうで怖かった。

gcloud container clusters get-credentials --zone asia-east1-a --project MY_PROJECT MY_KUBERNETES_CLUSTER_NAME

動作確認は bash 入りの自機でしかしていないので悪しからず…。