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.
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" ]
then
printf "\$KUBECONFIG not set.\n"
exit 1
fi
pod_label="$1"
pod_namespace="$2"
wait_seconds=4
last_container_id=""
get_container_id() {
echo $(kubectl get pods -l "app.kubernetes.io/name=${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
do
container_id=$(get_container_id)
# printf "ContainerID: %s\n" "$container_id"
if [[ "$container_id" != "$last_container_id" ]]
then
printf "ContainerID: %s\n" "$container_id"
last_container_id="${container_id}"
fi
sleep "${wait_seconds}"
done
To run the script, make sure you set the KUBECONFIG variable to point to a your config file: