These 5 unpopular and practical Kubectl usage skills, 99% of people should know

kubectl is an official command-line tool attached to K8s, which can easily operate K8s clusters. This article mainly introduces some other usages of kubectl. I hope readers have some basic K8s experience.

There is an article that also introduces some skills. I just found it when I was writing a blog, and I just want to share it.
Ready-to-use commands and tips for kubectl

1. Print the currently used API

# kubectl 的主要作用就是与 ApiServer 进行交互, 而交互的过程, 我们可以通过下面的方式来打印, # 这个命令尤其适合调试自己的api接口时使用.$ kubectl get ns -v=9

picture

2. Filter containers by status and delete

This is the command I learned here: Force Delete Evicted / Terminated Pods in Kubernetes

kubectl get pods --all-namespaces --field-selector status.phase=Pending -o json | \  jq '.items[] | "kubectl delete pods \(.metadata.name) -n \(.metadata.namespace)"' | \  xargs -n 1 bash -c
# 这个命令要拆开来看# 首先, 获取所有ns中状态为Pending的pods, 并以json形式输出# 这个语句其实由很多变体, 比如,我想查找Failed的状态, 或是某个deploymentkubectl get pods --all-namespaces --field-selector status.phase=Pending -o json 
# 针对json变量进行处理, 生成可用的脚本# 这里是我想介绍的重点, 利用jq以及kubectl的输出, 构建出可用的命令jq '.items[] | "kubectl delete pods \(.metadata.name) -n \(.metadata.namespace)"'
# 执行每一条命令# 注意, 这种命令一定要好好调试, 删掉预期之外的pod就不好了.xargs -n 1 bash -c
# 例如, 下面的语句可以找到所有的Pods并打印可以执行的语句kubectl get pods --all-namespaces --field-selector status.phase=Running -o json | \  jq '.items[] | "kubectl get pods \(.metadata.name) -o wide -n \(.metadata.namespace)"'
"kubectl get pods metrics-server-6d684c7b5-gtd6q -o wide -n kube-system""kubectl get pods local-path-provisioner-58fb86bdfd-98frc -o wide -n kube-system""kubectl get pods nginx-deployment-574b87c764-xppmx -o wide -n default"
# 当然, 如果只是删除单个NS下面的一些pods, 我会选择下面的方法, 但是它操作多个NS就很不方便了.kubectl -n default get pods  | grep Completed | awk '{print $1}' | xargs kubectl -n default delete pods

3. Count all pods running on a specific machine

kubectl can use two selectors, one is label, the other is field, you can see the introduction on the official website:

- Labels and Selectors
- Field Selectors​​​​​​​

# 它是一种选择器, 可以与上面的awk或者xargs配合使用.# 我个人平时都不喜欢用这个, 直接get全部pods, 然后grep查找感觉更快kubectl get pods --all-namespaces -o wide --field-selector spec.nodeName=pve-node1

4. Statistical distribution of the specific number of Pods on different machines

I don’t know if some readers have read my article: Implementation of fine-grained control pods scheme in kubernetes-based PaaS platform. The premise of balanced distribution is to know the distribution of pods on each machine. The best way is to make simple statistics after we get the pod information. This work can be achieved using awk. ​​​​​​​​

kubectl -n default get pods -o wide -l app="nginx" | awk '{print $7}'|\ awk '{ count[$0]++  }  END {    printf("%-35s: %s\n","Word","Count");   for(ind in count){
   
       printf("%-35s: %d\n",ind,count[ind]);   } }'
# 执行结果如下Word                               : CountNODE                               : 1pve-node1                          : 1pve-node2                          : 1
# awk的语法我没深入了解, 有兴趣的读者可以研究看看, 这里我就不求甚解了.

5. The use of kubectl proxy

You can understand that this command creates a layer of proxy for the K8s ApiServer. With this proxy, you can directly call the API without authentication. After startup, it is even possible to implement kubectl nesting dolls, here is an example:

# 当你没有设置kubeconfig而直接调用kubectl时kubectl get ns -v=9# 可以打印出下面类似的错误curl -k -v -XGET  -H "Accept: application/json, */*" -H "User-Agent: kubectl/v1.21.3 (linux/amd64) kubernetes/ca643a4" 'http://localhost:8080/api?timeout=32s'skipped caching discovery info due to Get "http://localhost:8080/api?timeout=32s": dial tcp 127.0.0.1:8080: connect: connection refused                     # 也就是说当你不指定kubeconfig文件时, kubectl会默认访问本机的8080端口# 那么我们先启动一个kubectl proxy, 然后指定监听8080, 再使用kubectl直接访问, 是不是就可行了呢, # 事实证明, 安全与预想一致.KUBECONFIG=~/.kube/config-symv3 kubectl proxy  -p 8080kubectl get nsNAME                           STATUS   AGEdefault                        Active   127d

The proxy started by default blocks certain APIs and has some restrictions, such as not being able to use exec to enter the pod, you can use kubectl proxy --help to see, for example

# 仅允许本机访问--accept-hosts='^localhost$,^127\.0\.0\.1$,^\[::1\]$': Regular expression for hosts that the proxy should accept.# 不允许访问下面的api, 也就是说默认没法exec进入容器--reject-paths='^/api/.*/pods/.*/exec,^/api/.*/pods/.*/attach': Regular expression for paths that the proxy should reject. Paths specified here will be rejected even accepted by --accept-paths.
# 想跳过exec的限制也很简单, 把reject-paths去掉就可以了kubectl proxy -p 8080 --keepalive 3600s --reject-paths='' -v=9

Some people say that kubectl proxy may have no effect, it may just be that you have no actual application scenarios. For example when I want to debug K8s dashboard code. If you use the kubeconfig file directly, I can't see the specific request process. If you add a layer of proxy forwarding and set -v=9, you will automatically get a logging tool, which is quite useful when debugging.

Summarize

kubectl is a powerful command-line tool. Above I just introduced a little exploration of its usage in my work, and I don’t encourage you to remember these commands. I just hope that when readers need it, they can remember that kubectl can have For similar functions, there is no need to study client-api for a few temporary needs.

Source: https://corvo.myseu.cn/2021/08/16/2021-08-16-kubectl%E7%9A%84%E5%A4%9A%E6%A0%B7%E7%94%A8% E6%B3%95/

 

Guess you like

Origin blog.csdn.net/LinkSLA/article/details/131952498