0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Kubernetes】Podをデバッグするスクリプト

Last updated at Posted at 2025-04-02

【Kubernetes】ノードをデバッグするスクリプト に続いてPodをデバッグするスクリプトです。
挙動としては指定したNamespaceのPodにエフェメラルコンテナを立ち上げて、シェルにログインします。

※ fzfとjqとkubectlが必要です。

pod-debugger.sh
#!/bin/bash
set -euo pipefail

function usage {
cat <<EOF >&2
指定したPodをDebugするコンテナを立ち上げるコマンド

Usage:
  $0 [Options]

Options:
  --no-copy
    Podをコピーしないで対象のポッドに直接コンテナを起動。
    終了後もPodにコンテナの残骸が残るので注意
  -h | --help
    ヘルプ
EOF
exit 1
}

function error {
  echo "[error] $1" >&2
  exit 1
}

function info {
  echo "[info] $1"
}

COPY=1
args=()
while [ "$#" != 0 ]; do
  case $1 in
    -h | --help ) usage ;;
    --no-copy   ) COPY=0 ;;
    -* | --*    ) error "$1 : 不正なオプションです" ;;
    *           ) args+=("$1") ;;
  esac
  shift
done
[ "${#args[@]}" != 0 ] && usage

# Namespaceの選択
NAMESPACE="$(kubectl get ns -o wide | sed '1d' | fzf --height 25% --header 'Select a namespace')"
NAMESPACE_NAME="$(echo $NAMESPACE | awk '{print $1}')"

# Podの選択
POD="$(kubectl get pod -n ${NAMESPACE_NAME} -o wide | sed '1d' | fzf --height 25% --header 'Select a pod')"
POD_NAME="$(echo $POD | awk '{print $1}')"

# 起動するイメージの選択
IMAGE=$(
cat <<EOF | fzf --height 25% --header "Select a image"
nicolaka/netshoot
public.ecr.aws/aws-cli/aws-cli
ubuntu:24.04
EOF
)

OPTIONS="-ti --image=$IMAGE"
if [[ "$COPY" == "1" ]]; then
  UNIX_TIME=$(date +%s)
  OPTIONS="$OPTIONS --copy-to="pod-debugger-$POD_NAME-$UNIX_TIME" --share-processes"
fi

echo kubectl -n $NAMESPACE_NAME debug $POD_NAME $OPTIONS -- /bin/bash
kubectl -n $NAMESPACE_NAME debug $POD_NAME $OPTIONS -- /bin/bash

# ノードデバッガーのPodを削除
for pod in $(kubectl -n $NAMESPACE_NAME get po -o json | jq -r ".items[].metadata.name" | grep -e "^pod-debugger"); do
  kubectl -n $NAMESPACE_NAME delete po $pod
done

使ってみる

pod-debugger.sh --no-copy

デバッグ対象のPodが所属するNamespaceを選択
スクリーンショット 2025-04-02 22.33.11.png

デバッグ対象のPodを選択
スクリーンショット 2025-04-02 22.33.47.png

起動するコンテナイメージを選択
スクリーンショット 2025-04-02 22.34.03.png

指定したNamespaceのPodにコンテナが立ち上がり、シェルにログインできます。
スクリーンショット 2025-04-02 22.34.22.png

ログアウト

exit
# Session ended, the ephemeral container will not be restarted but may be reattached using 'kubectl attach eks-pod-identity-agent-gq6l5 -c debugger-2d6f4 -i -t' if it is still running

--no-copy オプションを使うと、ログアウトしてもエフェメラルコンテナがpod内に残ってしまうのが玉に瑕
まあ、deploymentなりdaemonsetなりを再起動すれば消えるのですが、なんだかな、、、

スクリーンショット 2025-04-02 22.44.18.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?