備忘録として kubectl コマンドや tips をまとめる。
pod 情報を取得したい
1# all namespace
2$ kubectl get pods -A
3NAMESPACE NAME READY STATUS RESTARTS AGE
4kube-system coredns-5dd5756b68-ff4ql 1/1 Running 0 41s
5kube-system coredns-5dd5756b68-jpl5z 1/1 Running 0 41s
6kube-system etcd-docker-desktop 1/1 Running 0 46s
情報取得
kubectl get all はすべての resource を列挙しない。api-resources コマンドで api の種類を列挙し取得する
参考: kubectl get all は全リソースの情報を表示しない | text․superbrothers․dev
1kubectl get -A "$(kubectl api-resources --namespaced=true --verbs=list --output=name | tr "\n" "," | sed -e 's/,$//')"
kubectl api-resources でリソース名の csv を作成し、kubectl get “x,y,z,…” で指定したリソースを取得する。
kubectl get event を時系列でいい感じに見る
–sort-by で時系列にしつつ、-o の出力フォーマットを go-template にして tsv で表示できる。
1$ kubectl get events -A --sort-by='.metadata.creationTimestamp' -o 'go-template={{range .items}}{{.metadata.creationTimestamp}}{{"\t"}}{{.type}}{{"\t"}}{{.involvedObject.kind}}{{"\t"}}{{.reason}}{{"\t"}}{{.involvedObject.name}}{{"\t"}}{{.message}}{{"\n"}}{{end}}'
2
32023-01-01T07:22:33Z Normal Node NodeHasNoDiskPressure kind-control-plane Node kind-control-plane status is now: NodeHasNoDiskPressure
42023-01-01T07:22:33Z Normal Node NodeHasSufficientPID kind-control-plane Node kind-control-plane status is now: NodeHasSufficientPID
52023-01-01T07:22:33Z Normal Node NodeHasSufficientMemory kind-control-plane Node kind-control-plane status is now: NodeHasSufficientMemory
62023-01-01T07:22:34Z Normal Node Starting kind-control-plane Starting kubelet.
72023-01-01T07:22:34Z Normal Node NodeHasSufficientMemory kind-control-plane Node kind-control-plane status is now: NodeHasSufficientMemory
82023-01-01T07:22:34Z Normal Node NodeHasNoDiskPressure kind-control-plane Node kind-control-plane status is now: NodeHasNoDiskPressure
92023-01-01T07:22:34Z Normal Lease LeaderElection kube-controller-manager kind-control-plane_bfba68b7-7aa5-4746-9c6b-0addb52ea429 became leader
label selector だけでなく field selector を使う
pod や node の種類でフィルタリングする際には、label selector (-l) を利用することも多いが、field selector を使うと status 情報でフィルタリングできる。 大体の場合は、grep で済ますことも多いが、json や yaml などで取得したいというケースでは便利。
1$ kubectl get pods -A --field-selector status.phase=Running
2
3NAMESPACE NAME READY STATUS RESTARTS AGE
4kube-system coredns-565d847f94-5xxhc 1/1 Running 0 74m
5kube-system coredns-565d847f94-k7tpv 1/1 Running 0 74m
-o jsonpath で必要な情報だけを抜き出す
これは頻繁に使うので、様々な例がインターネットにある。 環境によって spec の中身が異なるため、まずは -oyaml で情報を確認して、jsonpath で抜き出す。
1# pod の乗っているノード名の取得
2$ kubectl get pod -nkube-system kube-apiserver-kind-control-plane -o jsonpath='{.spec.nodeName}'
3kind-control-plane
4
5# control plane の ip
6$ kubectl get nodes -l node-role.kubernetes.io/control-plane -o jsonpath='{.items[*].status.addresses[?(@.type=="InternalIP")].address}'
7172.18.0.2
8
9# jsonpath の range を使って出力を少し工夫したりもできる
10$ kubectl get nodes -l node-role.kubernetes.io/control-plane -o jsonpath='{range .items[*]}{.status.addresses[?(@.type=="InternalIP")].address}{"\n"}{end}'
11172.18.0.2
custom column と read コマンドを組み合わせて、bash で処理させる
すべての node や pod に対して操作をするような障害時のオペレーションで役に立つ。
1$ while read -r ns pod node
2do
3 echo "processing... $ns, $pod, $node"
4done < <(kubectl get pod --no-headers -A -ocustom-columns=NS:.metadata.namespace,POD:.metadata.name,NODE:.spec.nodeName)
5
6processing... kube-system, coredns-565d847f94-5xxhc, kind-control-plane
7processing... kube-system, coredns-565d847f94-k7tpv, kind-control-plane
8processing... kube-system, etcd-kind-control-plane, kind-control-plane
9processing... kube-system, kindnet-pgflw, kind-control-plane
10processing... kube-system, kube-apiserver-kind-control-plane, kind-control-plane
11processing... kube-system, kube-controller-manager-kind-control-plane, kind-control-plane
12processing... kube-system, kube-proxy-7g4tk, kind-control-plane
13processing... kube-system, kube-scheduler-kind-control-plane, kind-control-plane
14processing... local-path-storage, local-path-provisioner-684f458cdd-fdfzb, kind-control-plane
base64 エンコードされている secret を確認する
Linux や bash のバージョン次第でオプションが微妙に変わるが、下記で base64 エンコードされた文字を受け取って、decode できる。
1echo -n "base64 password: "; read -s pswd; echo "$pswd" | base64 --decode | less
特定の secret というのがある場合は、-o jsonpath をうまく使う。 下記は argocd の secret の値を base64 decode する例。
1kubectl get secret -nargocd argocd-initial-admin-secret -o jsonpath='{.data.password}' | base64 --decode | less
トラブルシュート系
クラスタ情報を dump する
1kubectl cluster-info dump
不具合のある pod をすぐに強制削除する
pod を強制的に消すと、finalizer によるゴミ resource 掃除や、アプリに SIGTERM ではなく SIGKILL が送られ graceful shutdown を行えない。 –force を使う場合はそのことを理解しておく必要がある。
1kubectl delete pod --grace-period=0 --force --wait=false
kubectl debug
target を指定しないと対象コンテナのプロセスをマウントできない。
1$ kubectl debug -nnamespace -it --image=ubuntu:latest mysql-7d48796987-qbtww --target=mysql -- bash
2
3# /proc/<pid>/root 配下に target となる pod の volume が存在する
4root@mysql-7d48796987-74tsw:/# ps aux
5USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
6root 1 0.0 0.0 4624 3888 pts/0 Ss 14:03 0:00 bash
7root 17 0.0 0.0 7060 1608 pts/0 R+ 14:06 0:00 ps aux
8
9# 分かりづらいが、process 配下の /root 内で対象のボリュームが確認できる
10root@mysql-7d48796987-74tsw:/# ls /proc/1/root/
11bin dev home lib32 libx32 mnt proc root sbin sys usr
12boot etc lib lib64 media opt product_uuid run srv tmp var
13
14root@mysql-7d48796987-74tsw:/# ls /proc/1/root/tmp
15mysql.sock
16
17# debugger コンテナのように名前をつけたい場合は -c で指定できる。付けない上記の例だと hash つきの debug 用コンテナが生成されていく
18$ kubectl debug -nnamespace -it --image=ubuntu:latest mysql-7d48796987-qbtww --target=mysql -c=debugger -- bash
19
20# pod が deployment で管理されている場合は、pod を delete すれば debug 用コンテナもあわせて削除できる
21# --rm オプションをサポートしてほしいところだ
22$ kubectl delete pod mysql-7d48796987-qbtww
kubectl krew について
krew plugin を入れることでコマンドをさらに便利にできる Kubectl plugins available · Krew
tree
1$ kubectl krew install tree
2
3 $ kubectl tree deployment grafana -nproduct-measurement
4NAMESPACE NAME READY REASON AGE
5product-measurement Deployment/grafana - 21h
6product-measurement └─ReplicaSet/grafana-96dd49547 - 21h
7product-measurement └─Pod/grafana-96dd49547-49czh True 21h
resource の依存状況を見ることができて理解しやすい。
neat
itaysk/kubectl-neat: Clean up Kuberntes yaml and json output to make it readable
yaml に不要な情報が多いから、それをフィルターして表示できるプラグイン。
1# last applied configuration などがない
2 $ kubectl neat get -- deployment grafana -nproduct-measurement
3apiVersion: apps/v1
4kind: Deployment
5metadata:
6 annotations:
7 deployment.kubernetes.io/revision: "1"
8 labels:
9 app: grafana
10 name: grafana
11 namespace: product-measurement
12spec:
13 progressDeadlineSeconds: 600
14 replicas: 1
15 revisionHistoryLimit: 10
16 selector:
17 matchLabels:
18 app: grafana
access-matrix
1$ kubectl access-matrix
2NAME LIST CREATE UPDATE DELETE
3apiservices.apiregistration.k8s.io ✔ ✔ ✔ ✔
4bindings ✔
5certificatesigningrequests.certificates.k8s.io ✔ ✔ ✔ ✔
6clusterrolebindings.rbac.authorization.k8s.io ✔ ✔ ✔ ✔
7clusterroles.rbac.authorization.k8s.io ✔ ✔ ✔ ✔
8componentstatuses ✔
9configmaps ✔ ✔ ✔ ✔
10controllerrevisions.apps ✔ ✔ ✔ ✔
11cronjobs.batch ✔ ✔ ✔ ✔
12csidrivers.storage.k8s.io ✔ ✔ ✔ ✔
13csinodes.storage.k8s.io ✔ ✔ ✔ ✔
14csistoragecapacities.storage.k8s.io ✔ ✔ ✔ ✔
15customresourcedefinitions.apiextensions.k8s.io ✔ ✔ ✔ ✔
16daemonsets.apps ✔ ✔ ✔ ✔
17deployments.apps ✔ ✔ ✔ ✔
18endpoints ✔ ✔ ✔ ✔
19endpointslices.discovery.k8s.io ✔ ✔ ✔ ✔
20events ✔ ✔ ✔ ✔
21events.events.k8s.io ✔ ✔ ✔ ✔
22flowschemas.flowcontrol.apiserver.k8s.io ✔ ✔ ✔ ✔
23horizontalpodautoscalers.autoscaling ✔ ✔ ✔ ✔
24ingressclasses.networking.k8s.io ✔ ✔ ✔ ✔
rolesum
アカウントごとに権限を調査できる。
1$ kubectl rolesum -n kube-system bootstrap-signer
2ServiceAccount: kube-system/bootstrap-signer
3Secrets:
4
5Policies:
6• [RB] kube-system/system:controller:bootstrap-signer ⟶ [R] kube-system/system:controller:bootstrap-signer
7 Resource Name Exclude Verbs G L W C U P D DC
8 secrets [*] [-] [-] ✔ ✔ ✔ ✖ ✖ ✖ ✖ ✖