Search code examples
kuberneteskubernetes-helm

kubectl get last restart time of a pod


as a preparation I'll tell what I know

When I run kubectl logs --previous <pod_name> I'll get last 20lines of logs before restart and timestamp when than happened, but I wanted to have that timestamp displayed when I run kubectl get pods as an additional column.

The kube docs on how to create custom columns show that

kubectl get pods <my_pod_name -o custom-columns=NAME:.metadata.name,RSRC:.metadata.resourceVersion
NAME           RSRC
submit-queue   610995

but my question is where is this metadata/spec stored??? where can I list all possible metadata so I know what column to search or write, and same for spec and any other possible column

I know I can look at the pod with kubectl describe pod <pod> but how do I translate fields there to this .metadata.name format ?

Part of my descirbe looks like so

MacBook-Pro% kubectl describe pod xxx
Name:         xxx
Namespace:    xx
Priority:     0
Node:         myname/myip
Start Time:   Tue, 23 Feb 2021 11:37:01 +0100
Labels:       app=xx
              app.kubernetes.io/instance=xx
              app.kubernetes.io/managed-by=Helm
              app.kubernetes.io/name=xx
              env=xx
              helm.sh/chart=xx
              pod-template-hash=yy
Annotations:  kubectl.kubernetes.io/restartedAt: 2020-10-23T11:21:09+02:00
Status:       Running
IP:           10.xx
IPs:
  IP:           10.xx
Controlled By:  ReplicaSet/xxx
Containers:
  my_app:
    Container ID:   docker://xxxx
    Image:          gcr.ioxxxx
    Image ID:       docker-pullable://gcrxxx
    Port:           8080/TCP
    Host Port:      0/TCP
    State:          Running
      Started:      Fri, 12 Mar 2021 11:34:42 +0100
    Last State:     Terminated
      Reason:       Error
      Exit Code:    143
      Started:      Fri, 05 Mar 2021 12:34:58 +0100
      Finished:     Fri, 12 Mar 2021 11:34:41 +0100

any thought how to get to Last State.Finished field ?

Would appreciate any help, thanks.


Solution

  • You can use kubectl get pod -o yaml to view your POD resource in the YAML format (or -o json if you prefer).

    In this format, you can see the metadata keys and values. e.g.:

    $ kubectl get po -o yaml my-nginx-5b56ccd65f-4vmms | head -n 5
    apiVersion: v1
    kind: Pod
    metadata:
      creationTimestamp: "2021-03-09T15:19:38Z"
      generateName: my-nginx-5b56ccd65f-
    

    You can also use kubectl explain pod to list and describe all possible fields associated with the pod API resource. It's possible to get the documentation of a specific field of a resource (e.g., kubectl explain pods.status.containerStatuses).


    To get the Last State.Finished value you can use:

    $ kubectl get pods my-nginx-5b56ccd65f-4vmms -o custom-columns=NAME:.metadata.name,FINISHED:.status.containerStatuses[*].lastState.terminated.finishedAt
    NAME                        FINISHED
    my-nginx-5b56ccd65f-4vmms   2021-03-09T15:35:45Z