📌
ibook
  • README
  • cheatsheet
    • bash
      • builtin
      • syntactic sugar
      • cmd
      • havefun
    • text-processing
      • awk
      • sed
      • html
      • json
      • regex
      • unicode
    • osx
    • curl
    • tricky
    • widget
    • proxy
    • colors
    • math
    • media
    • ssl
      • keystore
      • verification
      • server
      • client
      • tricky
    • windows
      • powershell
      • choco
      • wsl
      • wt
      • shortcut
      • clsid
      • env
      • shell:folder
  • vim
    • nvim
    • install
    • color
    • plugins
      • usage
      • other plugins
      • deprecated
    • tricky
    • viml
    • windows
    • troubleshooting
  • devops
    • admin tools
    • ssh
    • git
      • config
      • alias
      • submodule
      • eol
      • example
      • gerrit
        • gerrit API
      • github
      • troubleshooting
      • tricky
      • statistics
    • pre-commit
    • release-tools
    • tmux
      • cheatsheet
    • ansible
    • vault
    • artifactory
      • api
      • cli
      • aql
      • nginx cert
    • klocwork
      • kwadmin
      • kwserver
      • api
      • q&a
    • elk
    • mongodb
    • android
    • mobile
  • jenkins
    • config
      • windows
    • appearance
    • troubleshooting
    • jenkinsfile
      • utility
      • parallel
      • build
      • envvar
      • properties
      • trigger
      • node
    • script
      • job
      • build
      • stage
      • agent
      • security & authorization
      • exception
      • monitor
      • tricky
    • api
      • blueocean
    • cli
    • plugins
      • kubernetes
      • docker
      • shared-libs
      • lockable-resource
      • ansicolor
      • badge
      • groovy-postbuild
      • simple-theme
      • customizable-header
      • artifactory
      • jira-steps
      • job-dsl
      • build-timeline
      • crumbIssuer
      • coverage
      • uno-choice
      • tricky
  • virtualization
    • kubernetes
      • init
        • kubespray
        • kubeadm
          • environment
          • crio v1.30.4
          • docker v1.15.3
          • HA
        • addons
        • etcd
      • kubectl
        • pod
        • deploy
        • replicasets
        • namespace
        • secrets
      • node
      • certificates
      • events
      • kubeconfig
      • kubelet
      • troubleshooting
      • cheatsheet
      • auth
      • api
      • tools
        • monitor
        • helm
        • network
        • minikube
    • docker
      • run & exec
      • voume
      • remove
      • show info
      • dockerfile
      • dockerd
      • tricky
      • troubleshooting
      • windows
    • crio
    • podman
  • ai
    • prompt
  • osx
    • apps
      • init
      • brew
    • defaults
    • system
    • network
    • script
    • tricky
  • linux
    • devenv
    • util
      • time & date
      • output formatting
      • params
      • tricky
    • nutshell
    • disk
    • network
    • troubleshooting
    • system
      • apt/yum/snap
      • authorization
      • apps
      • x11
    • ubuntu
      • systemctl
      • x
    • rpi
  • programming
    • groovy
    • python
      • config
      • basic
      • list
      • pip
      • q&a
    • others
    • archive
      • angular
      • maven
      • mysql
        • installation
        • logs
      • ruby
        • rubyInstallationQ&A
  • tools
    • fonts
    • html & css
    • Jira & Confluence
    • node & npm
      • gitbook
      • hexo
      • github.page
      • code themes
    • app
      • microsoft office
      • vscode
      • virtualbox
      • iterm2
      • browser
      • skype
      • teamviewer
      • others
  • quotes
  • english
Powered by GitBook
On this page
  • what is kubectl
  • install
  • get
  • list
  • output format
  • apply
  • rollback

Was this helpful?

  1. virtualization
  2. kubernetes

kubectl

PreviousetcdNextpod

Last updated 8 months ago

Was this helpful?

reference:

install

[!NOTE] references:

info:

$ uname | awk '{print tolower($0)}'
darwin
$ curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt
v1.26.2
$ curl -LO https://storage.googleapis.com/kubernetes-release/release/`curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt`/bin/$(uname | awk '{print tolower($0)}')/amd64/kubectl
$ chmod +x ./kubectl
$ sudo mv ./kubectl /usr/local/bin/kubectl

# verify
$ kubectl version --client --short
Flag --short has been deprecated, and will be removed in the future. The --short output will become the default.
Client Version: v1.25.3
Kustomize Version: v4.5.
  • kubectl-convert

    [!NOTE] A plugin for Kubernetes command-line tool kubectl, which allows you to convert manifests between different API versions. This can be particularly helpful to migrate manifests to a non-deprecated api version with newer Kubernetes release.

    # intel
    $ curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/darwin/amd64/kubectl-convert"
    # apple silicon
    $ curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/darwin/arm64/kubectl-convert"
    
    $ chmod +x ./kubectl-convert
    $ sudo mv ./kubectl-convert /usr/local/bin/kubectl-convert
    $ sudo chown root: /usr/local/bin/kubectl-convert
  • sha256 check

    $ curl -LO https://storage.googleapis.com/kubernetes-release/release/`curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt`/bin/$(uname | awk '{print tolower($0)}')/amd64/kubectl
    $ curl -LO https://storage.googleapis.com/kubernetes-release/release/`curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt`/bin/$(uname | awk '{print tolower($0)}')/amd64/kubectl.sha256
    $ echo "$(cat kubectl.sha256)  kubectl" | shasum -a 256 --check

osx

# intel
$ curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/darwin/amd64/kubectl"

# apple silicon
$ curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/darwin/arm64/kubectl"

# or via brew
$ brew install kubectl

completion

[!NOTE] The Homebrew installation of bash-completion v2 sources all the files in the BASH_COMPLETION_COMPAT_DIR directory, that's why the latter two methods work

$ brew install bash-completion           # Bash 3.2
$ brew install bash-completion@2         # Bash 4.1+
$ kubectl completion bash > $(brew --prefix)/etc/bash_completion.d/kubectl

linux

$ curl -LO https://storage.googleapis.com/kubernetes-release/release/`curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt`/bin/$(uname | awk '{print tolower($0)}')/amd64/kubectl
$ chmod +x ./kubectl
$ sudo mv ./kubectl /usr/local/bin/kubectl

completion

$ echo 'source <(kubectl completion bash)' >> ~/.bash_profile
$ kubectl completion bash > /usr/local/etc/bash_completion.d/kubectl
$ echo 'alias k=kubectl' >> ~/.bash_profile
$ echo 'complete -o default -F __start_kubectl k' >> ~/.bash_profile

windows

> choco install kubernetes-cli

> cd %USERPROFILE%
> mkdir .kube
> touch .kube/config

get

reference:

  • -o custom-columns=<header>:<jsonpath>[,<header>:<jsonpath>]...

get all

$ kubectl get all -A

get cluster status

$ kubectl get cs
NAME                 STATUS    MESSAGE             ERROR
controller-manager   Healthy   ok
scheduler            Healthy   ok
etcd-1               Healthy   {"health":"true"}
etcd-2               Healthy   {"health":"true"}
etcd-0               Healthy   {"health":"true"}

get po

  • name

    $ kubectl -n devops get po -o custom-columns='NAME:metadata.name'
  • or

    $ kubectl -n devops get deploy jenkins -o custom-columns="NAME:metadata.name, IMAGES:..image"
    NAME              IMAGES
    jenkins   jenkins/jenkins:2.187
  • $ kubectl get pod -o=custom-columns=NAME:.metadata.name,STATUS:.status.phase,NODE:.spec.nodeName \
                      --all-namespaces
  • sort pods by nodeName

    $ kubectl get pods -o wide --sort-by="{.spec.nodeName}"
  • sort by restart count

    $ kubectl get pods --sort-by="{.status.containerStatuses[:1].restartCount}"
  • sort by age

    $ kubectl get replicasets -o wide --sort-by=.metadata.creationTimestamp
    • $ kubectl get pods --sort-by=.status.startTime
    • $ kubectl get pods --field-selector=status.phase=Pending \
                         --sort-by=.metadata.creationTimestamp |
                awk 'match($5,/^[1-5]d/) {print $0}'

get all images

$ kubectl get pods --all-namespaces \
                   -o jsonpath="{..image}" |
          tr -s '[[:space:]]' '\n' |
          sort |
          uniq -c

list

list image from a single deploy

$ kubectl -n devops get deployment jenkins -o=jsonpath='{.spec.template.spec.containers[:1].image}'
jenkins/jenkins:2.187
  • or

    $ kubectl -n devops get deploy jenkins -o jsonpath="{..image}"
    jenkins/jenkins:2.187
$ kubectl get pods --all-namespaces -o=jsonpath="{..image}" -l app=nginx
  • $ kubectl -n <namespace> get po \
        -o custom-columns='NAME:metadata.name,IMAGES:spec.containers[*].image'
  • $ kubectl -n <namespace> get po <pod_name> -o jsonpath="{..containerID}"
    
    # or
    $ kubectl -n <namespace> get po <pod_name> \
        -o go-template \
        --template="{{ range .status.containerStatuses }}{{ .containerID }}{{end}}"
$ kubectl get pods --all-namespaces -o jsonpath="{.items[*].spec.containers[*].image}"
  • or

    $ kubectl get pods --all-namespaces -o jsonpath="{..image}" |
      tr -s '[[:space:]]' '\n' |
      sort |
      uniq -c
$ kubectl -n kube-system get pods -o jsonpath="{..image}"
$ kubectl get po --all-namespaces \
           -o go-template \
           --template="{{range .items}}{{range .spec.containers}}{{.image}} {{end}}{{end}}"
  • $ kubectl get deploy \
            -o=jsonpath="{range .items[*]}{'\n'}{.metadata.name}{':\t'}{range .spec.template.spec.containers[*]}{.image}{', '}{end}{end}"

list all quota

$ for _i in $(kubectl get ns --no-headers | awk -F' ' '{print $1}'); do
    echo ------------- ${_i} ------------
    kubectl -n ${_i} describe quota
  done

check api server healthy

$ kubectl get apiservice
  • delete apiservers

    $ kubectl delete apiservice v1beta1.metrics.k8s.io

get apiservers

 $ kubectl get --raw=/apis

get apiresources

  • check available

    $ kubectl api-resources
    $ kubectl api-versions
  • check apiservices registered

    $ kubectl get apiservices.apiregistration.k8s.io
    $ kubectl get apiservices.apiregistration.k8s.io v1beta1.metrics.k8s.io -o yaml
    $ kubectl get apiservices.apiregistration.k8s.io
    NAME                                   SERVICE                      AVAILABLE                 AGE
    v1.                                    Local                        True                      4y
    v1.apps                                Local                        True                      4y
    v1.authentication.k8s.io               Local                        True                      4y
    v1.authorization.k8s.io                Local                        True                      4y
    v1.autoscaling                         Local                        True                      4y
    v1.batch                               Local                        True                      4y
    v1.monitoring.coreos.com               Local                        True                      168d
    v1.networking.k8s.io                   Local                        True                      4y
    v1.rbac.authorization.k8s.io           Local                        True                      4y
    v1.storage.k8s.io                      Local                        True                      4y
    v1beta1.admissionregistration.k8s.io   Local                        True                      4y
    v1beta1.apiextensions.k8s.io           Local                        True                      4y
    v1beta1.apps                           Local                        True                      4y
    v1beta1.authentication.k8s.io          Local                        True                      4y
    v1beta1.authorization.k8s.io           Local                        True                      4y
    v1beta1.batch                          Local                        True                      4y
    v1beta1.certificates.k8s.io            Local                        True                      4y
    v1beta1.coordination.k8s.io            Local                        True                      4y
    v1beta1.events.k8s.io                  Local                        True                      4y
    v1beta1.extensions                     Local                        True                      4y
    v1beta1.metrics.k8s.io                 kube-system/metrics-server   False (ServiceNotFound)   188d
    v1beta1.policy                         Local                        True                      4y
    v1beta1.rbac.authorization.k8s.io      Local                        True                      4y
    v1beta1.scheduling.k8s.io              Local                        True                      4y
    v1beta1.storage.k8s.io                 Local                        True                      4y
    v1beta2.apps                           Local                        True                      4y
    v2beta1.autoscaling                    Local                        True                      4y
    v2beta2.autoscaling                    Local                        True                      4y0
    
    $ kubectl get apiservices.apiregistration.k8s.io v1beta1.metrics.k8s.io -o yaml --export
    apiVersion: apiregistration.k8s.io/v1
    kind: APIService
    metadata:
      name: v1beta1.metrics.k8s.io
    spec:
      group: metrics.k8s.io
      groupPriorityMinimum: 100
      insecureSkipTLSVerify: true
      service:
        name: prometheus-adapter
        namespace: monitoring
      version: v1beta1
      versionPriority: 100
    status:
      conditions:
      - lastTransitionTime: 2022-08-15T14:10:39Z
        message: all checks passed
        reason: Passed
        status: "True"
        type: Available
  • troubleshooting

    [!NOTE|label:references:]

    $ kubectl api-resources
    error: unable to retrieve the complete list of server APIs: metrics.k8s.io/v1beta1: the server is currently unable to handle the request
    • references:

    $ kubectl get apiservices.apiregistration.k8s.io
    NAME                                   SERVICE                      AVAILABLE                 AGE
    v1beta1.metrics.k8s.io                 kube-system/metrics-server   False (ServiceNotFound)   188d
    
    # remove metrics.k8s.io
    $ kubectl delete apiservices.apiregistration.k8s.io v1beta1.metrics.k8s.io
    
    # debug
    $ kubectl get secrets $(kubectl -n kube-system get sa metrics-server -o 'jsonpath={.secrets[].name}')
    Error from server (NotFound): secrets "metrics-server-token-mr49q" not found
    
    $ kubectl get secrets $(kubectl -n kube-system get sa metrics-server -o 'jsonpath={.secrets[].name}') \
              -o "jsonpath={.data.ca\.crt}" |
              base64 -d |
              openssl x509 -text -noout |
              grep Not
    # get token
    $ kubectl get secrets $(kubectl -n kube-system get sa metrics-server -o 'jsonpath={.secrets[].name}') \
              -o "jsonpath={.data.token}" |
              base64 -d -w0
    # get namespace
    $ kubectl get secrets $(kubectl -n kube-system get sa metrics-server -o 'jsonpath={.secrets[].name}') \
              -o "jsonpath={.data.namespace}" |
              base64 -d -w0

check etcd

$ kubectl get --raw=/healthz/etcd
ok

output format

[!NOTE|label:references:]

apply

[!NOTE|label:referenecs]

  • oneline cmd

    $ cat << EOF | kubectl create -f -
    apiVersion: v1
    kind: Secret
    metadata:
      name: mysecret
    type: Opaque
    data:
      password: $(echo "admin" | base64)
      username: $(echo "1f2d1e2e67df" | base64)
    EOF
  • # Edit the last-applied-configuration annotations by type/name in YAML
    kubectl apply edit-last-applied deployment/nginx
    
    # Edit the last-applied-configuration annotations by file in JSON
    kubectl apply edit-last-applied -f deploy.yaml -o json

rollback

:

[!NOTE|label:references:] -

what is kubectl
kubectl
* Cheatsheet - Kubectl
* kubectl cheatsheet
23 Advanced kubectl commands
使用 kubectl 管理 Secret
JSONPath Support
Basic JSONPath Rules
Command line tool (kubectl)
* Custom columns
install and set up kubectl
install and set up kubectl on macos
install and set up kubectl on linux
install and set up kubectl on windows
Amazon EKS.pdf
installing or updating kubectl
output options
get where pods are running
or
or
list Container images by Pod
or
or
list all Container images in all namespaces
list Container images filtering by Pod namespace
list Container images using a go-template instead of jsonpath
or
#1223: "couldn't get resource list" error
#11772: Couldn't get resource list for metrics error
#157: couldn't get resource list for metrics.k8s.io/v1beta1: the server is currently unable to handle the request
Configure Service Accounts for Pods
Kubectl output options
Getting Custom Output From Kubectl With Examples
kube apply
Declarative Management of Kubernetes Objects Using Configuration Files
Understanding the Kubectl Apply Command
How kubectl apply command works?
edit-last-applied
** How do you rollback deployments in Kubernetes?
what is kubectl
install
osx
linux
windows
get
get all
get cluster status
get po
get all images
list
list image from a single deploy
list Container images by Pod
list all Container images in all namespaces
list Container images filtering by Pod namespace
list Container images using a go-template instead of jsonpath
list all quota
check api server healthy
get apiservers
get apiresources
check etcd
output format
apply
rollback
kubectl