重要
三个 kubectl 高频小技巧:自动补全、go-template 自定义输出、强制删除卡在 Terminating 的 namespace。
1. Kubectl 自动补全
1
2
3
| apt install bash-completion
echo "source <(kubectl completion bash)" >> ~/.bashrc
source ~/.bashrc
|
2. go-template 和 jsonpath 自定义输出
kubectl get -o wide 不够用时,用 go-template 或 jsonpath 提取自定义字段。
go-template 列出所有 Pod 的 UID:
1
2
| kubectl get pods --all-namespaces \
-o go-template='{{range .items}}{{.metadata.uid}}{{"\n"}}{{end}}'
|
jsonpath 提取 Istio IngressGateway 的 NodePort:
1
2
| kubectl get svc -n istio-system istio-ingressgateway \
-o jsonpath='{.spec.ports[?(@.name=="tcp-pilot-grpc-tls")].nodePort}'
|
| 输出格式 | 适用场景 | 语法复杂度 |
|---|
-o wide | 查看常用附加字段 | — |
-o jsonpath | 提取单个或少量字段 | 低 |
-o go-template | 多字段格式化输出、遍历 | 中 |
3. 强制删除 Terminating 的 Namespace
方案一(优先尝试):
1
| kubectl delete namespace <ns> --force --grace-period=0
|
方案二(方案一无效时):
1
| kubectl edit namespace <ns>
|
将 spec.finalizers 数组清空(改为 []),保存退出后 namespace 自动删除。
Namespace 无法删除通常是因为还有资源引用。可以先排查:
1
2
| kubectl api-resources --namespaced=true -o name \
| xargs -n1 kubectl get --show-kind --ignore-not-found -n <ns>
|
参考