コンテンツにスキップ

kubectl

分類変えるかも…

オプション

kubeconfigファイル指定

環境変数KUBECONFIGか、オプション--kubeconfigに指定する

コンテキスト

一覧

kubectl config get-contexts

切り替え

kubectl config use-contexts <context-name>

設定

kubeconfigのマージ

$ KUBECONFIG=new-kubeconfig.yaml:$HOME/.kube/config kubectl config view --flatten > $HOME/.kube/tmp
$ mv $HOME/.kube/tmp $HOME/.kube/config

タブ補完

source <(kubectl completion bash)
complete -o default -F __start_kubectl kc

[oc / kubectl] コマンドや引数の補完設定 【completion】 - zaki work log

kindhelmも同じ要領。

tab押下で _get_comp_words_by_ref: command not found エラーが出るときは、bash-completionが無いのでパッケージ追加する。

$ kubectl get -bash: _get_comp_words_by_ref: command not found

create

secret

ファイルのsecret

キー名: ファイル内容のsecret作る

$ cat sample.txt 
hello
kubernetes!
$ kubectl create secret generic sample-secret --from-file=lines=sample.txt 
secret/sample-secret created
$ kubectl get secret sample-secret
NAME            TYPE     DATA   AGE
sample-secret   Opaque   1      6s
$ kubectl get secret sample-secret -o yaml
apiVersion: v1
data:
  lines: aGVsbG8Ka3ViZXJuZXRlcyEK
kind: Secret
metadata:
  creationTimestamp: "2021-07-07T12:12:03Z"
  name: sample-secret
  namespace: default
  resourceVersion: "1041860"
  uid: 9675c818-cb9b-4b7f-a29c-c60bf5a908aa
type: Opaque
$ kubectl get secret sample-secret -o jsonpath='{.data.lines}' | base64 -d
hello
kubernetes!

これはConfigMapと同じ

key=valueのsecret

$ kubectl create secret generic sample-secret --from-literal=username=zaki
secret/sample-secret created

このコマンド実行で以下のsecretリソースが作成される。

$ kubectl get secret sample-secret -o yaml
apiVersion: v1
data:
  username: emFraQ==
kind: Secret
metadata:
  creationTimestamp: "2022-03-24T02:57:06Z"
  name: sample-secret
  namespace: default
  resourceVersion: "298054"
  uid: 35c9b58a-247d-4243-b292-193d811f140a
type: Opaque

マニフェストでsecret

マニュフェストから作成する場合は、base64エンコード済みであること。

$ cat secret-sample.yaml 
apiVersion: v1
data:
  username: emFraQ==
kind: Secret
metadata:
  name: sample-secret2
  namespace: default
type: Opaque
$ kubectl apply -f secret-sample.yaml 
secret/sample-secret2 created
$ kubectl get secret sample-secret2 -o yaml
apiVersion: v1
data:
  username: emFraQ==
kind: Secret
metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"v1","data":{"username":"emFraQ=="},"kind":"Secret","metadata":{"annotations":{},"name":"sample-secret2","namespace":"default"},"type":"Opaque"}
  creationTimestamp: "2022-03-24T03:01:32Z"
  name: sample-secret2
  namespace: default
  resourceVersion: "298241"
  uid: a1ae0bf1-3434-4f3d-88d3-a1bb33dee6ac
type: Opaque

patch

値の更新

kubectl patch -n namespace pdb resource -p '{ "spec": { "maxUnavailable": 0 }}'

run

ワーク用のpodをデプロイする

$ kubectl run work-pod --image=fedora --command -- tail -f /dev/null

マニフェストにするとこんな感じ

kind: Pod
apiVersion: v1
metadata:
  name: work-pod
spec:
  containers:
  - name: work-pod
    image: fedora
    command:
    - tail
    - -f
    - /dev/null

expose

podベースでserviceを作成

$ kubectl expose pod <pod-name> --port 80

config

[kubectl / oc]コンテキストやクラスタ情報の確認 (コマンドメモ) - zaki work log

~/.kube/config($KUBECONFIG)の内容から証明書のデータをマスクした情報

$ kubectl config view

現在のクラスタ情報

$ kubectl cluster-info 
Kubernetes control plane is running at https://192.168.0.121:6443
CoreDNS is running at https://192.168.0.121:6443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy
Metrics-server is running at https://192.168.0.121:6443/api/v1/namespaces/kube-system/services/https:metrics-server:/proxy

To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.

KUBECONFIGで持っているクラスタ一覧

$ kubectl config get-clusters
NAME
cluster-c2daobwhbsg
kind-multi-1.15
zks
kind-kind
kind-multicluster
kubernetes
local-k3s
oci-k3s-le
oci-k3s
sample-cluster

コンテキスト情報

$ kubectl config get-contexts
CURRENT   NAME                          CLUSTER               AUTHINFO                               NAMESPACE
          context-c2daobwhbsg           cluster-c2daobwhbsg   user-c2daobwhbsg                       
          kind-kind                     kind-kind             kind-kind                              
          kind-multi-1.15               kind-multi-1.15       kind-multi-1.15                        
          kind-multicluster             kind-multicluster     kind-multicluster                      
          kubernetes-admin@kubernetes   kubernetes            kubernetes-admin                       
          kubernetes-admin@zks          zks                   kubernetes-admin                       
          local-k3s                     local-k3s             local-k3s                              
          oci-k3s                       oci-k3s               oci-k3s                                
*         oci-k3s-le                    oci-k3s-le            oci-k3s-le                             
          sample-cluster                sample-cluster        clusterUser_sample-rg_sample-cluster  

現在のコンテキスト

$ kubectl config current-context
oci-k3s-le

コンテキストをセットする

$ kubectl config use-context k3d-k3s-default
Switched to context "k3d-k3s-default".

delete

指定namespaceの指定typeを全部消す

$ kubectl delete pvc -n zzz --all

wait

リソースが指定の条件になるまで待つ。
podがrunningになるまで待つには以下。

kubectl wait --for=jsonpath='{.status.phase}'=Running pod/*****

get

全てのリソース

kubectl get allだと全リソースが対象ではないが、本当にすべてのリソースを取得するには以下

kubectl get "$(kubectl api-resources --namespaced=true --verbs=list -o name | tr "\n" "," | sed -e 's/,$//')"

pluginを使ってサブコマンドにしておくと便利。
※ rootで実行

cat <<'EOL' > /usr/local/bin/kubectl-get_all
#!/usr/bin/env bash

set -e -o pipefail; [[ -n "$DEBUG" ]] && set -x

exec kubectl get "$(kubectl api-resources --namespaced=true --verbs=list --output=name | tr "\n" "," | sed -e 's/,$//')" "$@"
EOL
chmod +x /usr/local/bin/kubectl-get_all

実行

kubectl get-all -n awx

eventで作成時ソート

kubectl get event --sort-by='.metadata.creationTimestamp'

ヘルスチェック

$kubectl get --raw='/readyz'
ok

あるいは

$ kubectl get --raw='/readyz?verbose'
[+]ping ok
[+]log ok
[+]etcd ok
[+]etcd-readiness ok
[+]informer-sync ok
[+]poststarthook/start-kube-apiserver-admission-initializer ok
[+]poststarthook/generic-apiserver-start-informers ok
[+]poststarthook/priority-and-fairness-config-consumer ok
[+]poststarthook/priority-and-fairness-filter ok
[+]poststarthook/storage-object-count-tracker-hook ok
[+]poststarthook/start-apiextensions-informers ok
[+]poststarthook/start-apiextensions-controllers ok
[+]poststarthook/crd-informer-synced ok
[+]poststarthook/start-service-ip-repair-controllers ok
[+]poststarthook/rbac/bootstrap-roles ok
[+]poststarthook/scheduling/bootstrap-system-priority-classes ok
[+]poststarthook/priority-and-fairness-config-producer ok
[+]poststarthook/start-system-namespaces-controller ok
[+]poststarthook/bootstrap-controller ok
[+]poststarthook/start-cluster-authentication-info-controller ok
[+]poststarthook/start-kube-apiserver-identity-lease-controller ok
[+]poststarthook/start-deprecated-kube-apiserver-identity-lease-garbage-collector ok
[+]poststarthook/start-kube-apiserver-identity-lease-garbage-collector ok
[+]poststarthook/start-legacy-token-tracking-controller ok
[+]poststarthook/aggregator-reload-proxy-client-cert ok
[+]poststarthook/start-kube-aggregator-informers ok
[+]poststarthook/apiservice-registration-controller ok
[+]poststarthook/apiservice-status-available-controller ok
[+]poststarthook/kube-apiserver-autoregistration ok
[+]autoregister-completion ok
[+]poststarthook/apiservice-openapi-controller ok
[+]poststarthook/apiservice-openapiv3-controller ok
[+]poststarthook/apiservice-discovery-controller ok
[+]shutdown ok
readyz check passed

label

リソースのラベルを追加/変更/削除する

追加

$ kubectl label pod rsync-pod app=rsync
pod/rsync-pod labeled
$ kubectl get pod --show-labels
NAME                       READY   STATUS    RESTARTS   AGE   LABELS
rsync-pod                  1/1     Running   3          28d   app=rsync
sockserv-db66b7df7-rtcv9   1/1     Running   1          17d   app=sockserv,pod-template-hash=db66b7df7

更に追加

$ kubectl label pod rsync-pod state=normal
pod/rsync-pod labeled
$ kubectl get pod -l app=rsync --show-labels
NAME        READY   STATUS    RESTARTS   AGE   LABELS
rsync-pod   1/1     Running   3          28d   app=rsync,state=normal

複数まとめても可

$ kubectl label node k3s-node1 label1=foo label2=bar label3=baz
node/k3s-node1 labeled

更新

既に存在する場合はエラーになる。

$ kubectl label pod rsync-pod state=error
error: 'state' already has a value (normal), and --overwrite is false

が、メッセージにある通り--overwriteを追加すれば上書きできる。

kubectl label pod rsync-pod state=error --overwrite
pod/rsync-pod labeled
kubectl get pod -l app=rsync --show-labels
NAME        READY   STATUS    RESTARTS   AGE   LABELS
rsync-pod   1/1     Running   3          28d   app=rsync,state=error

削除

ラベルのキーに-を付与したものをセットすれば削除される。

kubectl label pod rsync-pod state-

drain

大抵はDaemonSetのpodが動いているので--ignore-daemonsetsオプションを付ける。

kubectl drain k3s-node2 --force --ignore-daemonsets

ノードを完全にクラスタから除外するにはさらにkubectl delete node <node-name>する。