運用でよく使う kubectl コマンド


Posted on Sun, Nov 5, 2023
Tags kubernetes, linux

備忘録として kubectl コマンドや tips をまとめる。

# kubectl と都度打たずに省略できるようにする 
alias k=kubectl

pod 情報を取得したい

# all namespace
$ kubectl get pods -A
NAMESPACE     NAME                                     READY   STATUS    RESTARTS   AGE
kube-system   coredns-5dd5756b68-ff4ql                 1/1     Running   0          41s
kube-system   coredns-5dd5756b68-jpl5z                 1/1     Running   0          41s
kube-system   etcd-docker-desktop                      1/1     Running   0          46s

情報取得

kubectl get all はすべての resource を列挙しない。api-resources コマンドで api の種類を列挙し取得する

参考: kubectl get all は全リソースの情報を表示しない | text․superbrothers․dev

kubectl 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 で表示することができる

$ 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}}'

2023-01-01T07:22:33Z    Normal  Node    NodeHasNoDiskPressure   kind-control-plane      Node kind-control-plane status is now: NodeHasNoDiskPressure
2023-01-01T07:22:33Z    Normal  Node    NodeHasSufficientPID    kind-control-plane      Node kind-control-plane status is now: NodeHasSufficientPID
2023-01-01T07:22:33Z    Normal  Node    NodeHasSufficientMemory kind-control-plane      Node kind-control-plane status is now: NodeHasSufficientMemory
2023-01-01T07:22:34Z    Normal  Node    Starting        kind-control-plane      Starting kubelet.
2023-01-01T07:22:34Z    Normal  Node    NodeHasSufficientMemory kind-control-plane      Node kind-control-plane status is now: NodeHasSufficientMemory
2023-01-01T07:22:34Z    Normal  Node    NodeHasNoDiskPressure   kind-control-plane      Node kind-control-plane status is now: NodeHasNoDiskPressure
2023-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 などで取得したいというケースでは便利。

$ kubectl get pods -A --field-selector status.phase=Running

NAMESPACE            NAME                                         READY   STATUS    RESTARTS   AGE
kube-system          coredns-565d847f94-5xxhc                     1/1     Running   0          74m
kube-system          coredns-565d847f94-k7tpv                     1/1     Running   0          74m

-o jsonpath で必要な情報だけを抜き出す

これは頻繁に使うので、様々な例がインターネットにある。環境によって spec の中身が異なるため、まずは -oyaml で情報を確認して、jsonpath で抜き出す

# pod の乗っているノード名の取得
$ kubectl get pod -nkube-system kube-apiserver-kind-control-plane -o jsonpath='{.spec.nodeName}'
kind-control-plane

# control plane の ip
$ kubectl get nodes -l node-role.kubernetes.io/control-plane -o jsonpath='{.items[*].status.addresses[?(@.type=="InternalIP")].address}'
172.18.0.2

# jsonpath の range を使って出力を少し工夫したりもできる
$ kubectl get nodes -l node-role.kubernetes.io/control-plane -o jsonpath='{range .items[*]}{.status.addresses[?(@.type=="InternalIP")].address}{"\n"}{end}'
172.18.0.2

custom column と read コマンドを組み合わせて、bash で処理させる

すべての node や pod に対して操作をするみたいな障害時のオペレーションで役に立つ

$ while read -r ns pod node
do
    echo "processing... $ns, $pod, $node"
done < <(kubectl get pod --no-headers -A -ocustom-columns=NS:.metadata.namespace,POD:.metadata.name,NODE:.spec.nodeName)

processing... kube-system, coredns-565d847f94-5xxhc, kind-control-plane
processing... kube-system, coredns-565d847f94-k7tpv, kind-control-plane
processing... kube-system, etcd-kind-control-plane, kind-control-plane
processing... kube-system, kindnet-pgflw, kind-control-plane
processing... kube-system, kube-apiserver-kind-control-plane, kind-control-plane
processing... kube-system, kube-controller-manager-kind-control-plane, kind-control-plane
processing... kube-system, kube-proxy-7g4tk, kind-control-plane
processing... kube-system, kube-scheduler-kind-control-plane, kind-control-plane
processing... local-path-storage, local-path-provisioner-684f458cdd-fdfzb, kind-control-plane

トラブルシュート系

クラスタ情報を dump する

kubectl cluster-info dump

不具合のある pod をすぐに強制削除する

pod を強制的に消すと、finalizer によるゴミ resource 掃除や、アプリに SIGTERM ではなく SIGKILL が送られ graceful shutdown ができないため、使う場合はそれを理解しておく必要がある。

kubectl delete pod --grace-period=0 --force --wait=false

kubectl debug

$ kubectl debug -nnamespace -it --image=ubuntu:latest mysql-7d48796987-qbtww -cmysql  -- bash

# /proc/<pid>/root 配下に target となる pod の volume が存在する
root@mysql-7d48796987-74tsw:/# ps aux
USER         PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root           1  0.0  0.0   4624  3888 pts/0    Ss   14:03   0:00 bash
root          17  0.0  0.0   7060  1608 pts/0    R+   14:06   0:00 ps aux

root@mysql-7d48796987-74tsw:/# ls /proc/1/root/
bin   dev  home  lib32  libx32  mnt  proc          root  sbin  sys  usr
boot  etc  lib   lib64  media   opt  product_uuid  run   srv   tmp  var
root@mysql-7d48796987-74tsw:/# ls /proc/1/root/tmp
mysql.sock

kubectl krew について

krew plugin を入れることでコマンドをさらに便利にできる Kubectl plugins available · Krew

tree

$ kubectl krew install tree

 $ kubectl tree deployment grafana -nproduct-measurement
NAMESPACE            NAME                             READY  REASON  AGE
product-measurement  Deployment/grafana               -              21h
product-measurement  └─ReplicaSet/grafana-96dd49547   -              21h
product-measurement    └─Pod/grafana-96dd49547-49czh  True           21h

ahmetb/kubectl-tree: kubectl plugin to browse Kubernetes object hierarchies as a tree 🎄 (star the repo if you are using)

resource の依存状況を見れることができて理解しやすい

neat

itaysk/kubectl-neat: Clean up Kuberntes yaml and json output to make it readable

yaml に不要な情報が多いから、それをフィルターして表示することができるプラグイン

# last applied configuration などがない
 $ kubectl neat get -- deployment grafana -nproduct-measurement
apiVersion: apps/v1
kind: Deployment
metadata:
  annotations:
    deployment.kubernetes.io/revision: "1"
  labels:
    app: grafana
  name: grafana
  namespace: product-measurement
spec:
  progressDeadlineSeconds: 600
  replicas: 1
  revisionHistoryLimit: 10
  selector:
    matchLabels:
      app: grafana

access-matrix

$ kubectl access-matrix
NAME                                                          LIST  CREATE  UPDATE  DELETE
apiservices.apiregistration.k8s.io                            ✔     ✔       ✔       ✔
bindings                                                            ✔
certificatesigningrequests.certificates.k8s.io                ✔     ✔       ✔       ✔
clusterrolebindings.rbac.authorization.k8s.io                 ✔     ✔       ✔       ✔
clusterroles.rbac.authorization.k8s.io                        ✔     ✔       ✔       ✔
componentstatuses                                             ✔
configmaps                                                    ✔     ✔       ✔       ✔
controllerrevisions.apps                                      ✔     ✔       ✔       ✔
cronjobs.batch                                                ✔     ✔       ✔       ✔
csidrivers.storage.k8s.io                                     ✔     ✔       ✔       ✔
csinodes.storage.k8s.io                                       ✔     ✔       ✔       ✔
csistoragecapacities.storage.k8s.io                           ✔     ✔       ✔       ✔
customresourcedefinitions.apiextensions.k8s.io                ✔     ✔       ✔       ✔
daemonsets.apps                                               ✔     ✔       ✔       ✔
deployments.apps                                              ✔     ✔       ✔       ✔
endpoints                                                     ✔     ✔       ✔       ✔
endpointslices.discovery.k8s.io                               ✔     ✔       ✔       ✔
events                                                        ✔     ✔       ✔       ✔
events.events.k8s.io                                          ✔     ✔       ✔       ✔
flowschemas.flowcontrol.apiserver.k8s.io                      ✔     ✔       ✔       ✔
horizontalpodautoscalers.autoscaling                          ✔     ✔       ✔       ✔
ingressclasses.networking.k8s.io                              ✔     ✔       ✔       ✔

rolesum

アカウントごとに権限を調査できる

$ kubectl rolesum -n kube-system bootstrap-signer
ServiceAccount: kube-system/bootstrap-signer
Secrets:

Policies:
[RB] kube-system/system:controller:bootstrap-signer ⟶  [R] kube-system/system:controller:bootstrap-signer
  Resource  Name  Exclude  Verbs  G L W C U P D DC
  secrets   [*]     [-]     [-]   ✔ ✔ ✔ ✖ ✖ ✖ ✖ ✖

ctx, ns

$ k ctx

$ k ns
Context "kind-kind" modified.
Active namespace is "kube-system".