Getting Pod ID and container ID of a container when it restarts

I need to know how to get a Pod-ID (UID) and Container-ID when a pod restarted.

I have a container which monitor a specific pod with its pod ID and container ID as argument. I need to spawn it every time the target pod restarted with its Pod-ID/container-ID.

In general we can get it using kubectl, but we need it at run time to create and deploy our container.

Thank You.

Hi satyabratabharati:

Maybe not exactly what you need, but I hope it helps you building your own solution.
You mention that you use kubectl to redeploy your monitoring pod, so I’ve built a quick & dirty solution (to get the containerID):

#!/usr/bin/env bash
set -e

if [ -z "$KUBECONFIG" ]
    printf "\$KUBECONFIG not set.\n"
    exit 1


get_container_id() {
    echo $(kubectl get pods -l "${pod_label}" -n "${pod_namespace}" -o json | jq -r '.items[].status.containerStatuses[].containerID' | tr -d 'containerd://')

 printf 'Watching namespace "%s" (with label "%s") ... \n' "${pod_namespace}" "${pod_label}"
while true
    # printf "ContainerID: %s\n" "$container_id"
    if [[ "$container_id" != "$last_container_id" ]]
        printf "ContainerID: %s\n" "$container_id"
    sleep "${wait_seconds}"

To run the script, make sure you set the KUBECONFIG variable to point to a your config file:

$ export KUBECONFIG=~/repos/vagrant/k3s-ubuntu-cluster/kubeconfig
$ ./ "argocd-server" "argocd"
Watching namespace "argocd" (with label "argocd-server") ... 
ContainerID: 21281939115633b63455b13b6079528b37f904f9ffb268b190bf0

If I force the restart of the pod, using:

$ kubectl -n argocd rollout restart deployment argocd-server
deployment.apps/argocd-server restarted

Then, the output of the script running in a separate terminal:

 $ ./ "argocd-server" "argocd"                                                                                                     130 ↵
Watching namespace "argocd" (with label "argocd-server") ... 
ContainerID: 21281939115633b63455b13b6079528b37f904f9ffb268b190bf0
ContainerID: 21281939115633b63455b13b6079528b37f904f9ffb268b190bf0 ull
ContainerID: 08047900167b20192704669334768182f825281777f540

There are some transient effects while the pod is being created but it gets the job done :wink:

A more elaborated solution (written in Go) may be built following the example in client-go/examples/in-cluster-client-configuration at master · kubernetes/client-go · GitHub and deployed inside the cluster.

Best regards,