kubernetesのpod内でstraceをrunning processにアタッチしたい

問題

kubernetesのpod内で strace コマンドの -p オプションを使い、実行中のプロセスにアタッチしようとすると以下のエラーが出る。

# strace -p 1
strace: attach: ptrace(PTRACE_SEIZE, 1): Operation not permitted

原因

strace が内部的に利用している ptrace システムコールのコンテナ内での実行が、セキュリティ担保のためデフォルトでは禁止されている。

対処

以下のように、 spec.containers.securityContext.capabilities にて ptrace の実行を許可するとコンテナ内での srace の実行が可能になる。
※ 「原因」に記載の理由から、デバッグしたい時のみ一次的に追加するのがベターかと思います。

apiVersion: apps/v1
kind: Deployment
metadata:
  creationTimestamp: null
  labels:
    run: nginx
  name: nginx
spec:
  replicas: 1
  selector:
    matchLabels:
      run: nginx
  strategy: {}
  template:
    metadata:
      creationTimestamp: null
      labels:
        run: nginx
    spec:
      containers:
      - image: nginx
        name: nginx
        # DEBUG用
        securityContext:
          capabilities:
            add:
            - SYS_PTRACE
        resources: {}
status: {}

その他

dockerの場合は --cap-add sys_ptracedocker run 実行の際に付与することで、同様に実行可能になる。

qiita.com

/* https://sunrise033.com/entry/hatena-blog-how-to-hierarchicalize-categories */