DEV Community

Cover image for How to get timestamp of all Kubernetes nodes without SSH to them
1Link.Fun
1Link.Fun

Posted on

How to get timestamp of all Kubernetes nodes without SSH to them

In some cases, you may need to get latest timestamp of ALL kubernetes nodes, instead of SSH to every one of them and issue date command, you can do this by kubectl and below script.

#!/bin/bash

# Get the name of the first DaemonSet in the kube-system namespace
first_daemonset=$(kubectl get daemonsets -n kube-system -o jsonpath='{.items[0].metadata.name}')

echo Collecting timestamp across the cluster nodes by using DaemonSet $first_daemonset

# Get the list of pod names and their corresponding node names controlled by the first DaemonSet
pods_info=$(kubectl get pods -n kube-system -o jsonpath='{range .items[?(@.metadata.ownerReferences[0].name=="'$first_daemonset'")]}{.metadata.name}{"\t"}{.spec.nodeName}{"\n"}{end}')

# Loop through each pod and execute the date command
while IFS=$'\t' read -r pod node; do
    # Get the name of the first container in the pod
    container_name=$(kubectl get pod -n kube-system $pod -o jsonpath='{.spec.containers[0].name}')

    if [ -z "$container_name" ]; then
        echo "No containers found in pod $pod"
        continue
    fi

    # Execute the date command inside the selected container
    pod_date=$(kubectl exec -n kube-system $pod -c $container_name -- date)
    echo "node: $node, date: $pod_date"
done <<< "$pods_info"
Enter fullscreen mode Exit fullscreen mode

Here is how it works:

  • I get the first daemonset name in kube-system namespace, normally, it should be the CNI plugin, but it doesn't matter if it's not, as long as it's a daemonset, its pods should runs on every nodes.

  • I then get the pod info list of the daemonset, for each of them I got {pod name} {node name}

  • Then I iterate the pod info list, for each of them, I firstly get the first container name of the pod (to execute date command in), then I use kubectl exec to run the date command in it

  • So finally, I got everything, and print the result in node: <node name>, date: <date command output>

The result be like:

Collecting timestamp across the cluster nodes by using DaemonSet rke2-canal
node: test-worker-2, date: Mon Jul 29 08:44:30 UTC 2024
node: test-worker-3, date: Mon Jul 29 08:44:28 UTC 2024
node: test-worker-1, date: Mon Jul 29 08:44:32 UTC 2024
node: test-master, date: Mon Jul 29 08:44:31 UTC 2024
Enter fullscreen mode Exit fullscreen mode

Problem solved!

Top comments (0)