如何通过kubectl custom-columns获取默认列并添加Pod IP列?
Hey there! I totally get your frustration with kubectl's custom columns overriding the default ones—this used to trip me up too. Let's break down each of your questions and build the exact custom columns command that matches the default output plus your desired PODIP column.
1. Replicating the READY column (e.g., 2/2, 0/1)
The default READY value counts ready containers vs. total containers in the pod. Use Go template functions to calculate this:
len(.spec.containers)returns the total number of containers in the podlen(.status.containerStatuses[?(@.ready==true)])counts how many containers are marked ready
Add this to your custom column definition:READY:{{len .status.containerStatuses[?(@.ready==true)]}}/{{len .spec.containers}}
2. Matching the default STATUS column (handling Evicted and other states)
The default STATUS combines .status.phase and .status.reason dynamically:
- Shows
Running(from.status.phase) when the pod is healthy - Displays
.status.reasonfor states likeEvicted,CrashLoopBackOff, etc. - Falls back to
.status.phaseif no reason exists (e.g.,Pendingpods)
Use a conditional Go template to replicate this logic:STATUS:{{if ne .status.reason ""}}{{.status.reason}}{{else}}{{.status.phase}}{{end}}
3. Summing all container restart counts for RESTARTS
Your current command only fetches the first container's restarts. To sum all containers' restart counts, use the sum function on the array of restart values:RESTARTS:{{sum .status.containerStatuses[*].restartCount}}
4. Getting the AGE column (relative running time)
Kubectl includes a built-in age template function that converts the pod's creation timestamp to human-readable relative time (like 5m, 2d). Pair it with the pod's creation timestamp:AGE:{{age .metadata.creationTimestamp}}
Full Command
Putting it all together, here's the command that replicates the default columns plus your PODIP column:
kubectl get pod -o custom-columns="NAME:.metadata.name,READY:{{len .status.containerStatuses[?(@.ready==true)]}}/{{len .spec.containers}},STATUS:{{if ne .status.reason \"\"}}{{.status.reason}}{{else}}{{.status.phase}}{{end}},RESTARTS:{{sum .status.containerStatuses[*].restartCount}},AGE:{{age .metadata.creationTimestamp}},PODIP:.status.podIP"
Quick Notes
- If you're using Windows, adjust quote escaping (replace
\"with"or wrap the entire custom-columns string in single quotes) - For newly created pods with no container statuses, some values may appear empty—this matches default kubectl behavior
内容的提问来源于stack exchange,提问作者RubenLaguna

