I am new to k8s and I am running into a little problem here.
Here's the context:
I need to invoke kubectl delete [podname]
via a crontask once a day, and wait until k8s recreates the pod, then log into the container in that pod and run a shell command.
So I query the deployment and get something like this:
user@host:~$ kubectl get pods
NAME READY STATUS RESTARTS AGE
firstpod-123456789-something 1/1 Running 570 2d
secondpod-http-backend-something 1/1 Running 597 2d
then I wrote a bash script that would delete the pods in a 5 minutes interval. That's the easy part.
Suppose I invoke kubectl delete firstpod-123456789-something
and wait for k8s to recreate a new pod. That new pod would have a new name like firstpod-[some random hash here]-something
The problem is that I need to capture the name of that pod in my bash script so then I can exec a command in that pod like uname -a
or whatever as to verify that the new pod is up and running just fine.
I googled it and read the kubectl docs but I don't think there's an easy way to do this via a bash script? I am assuming that the only way to get the pod name here would be via the k8s API?
I am happy to use any solution at this point. I wonder if there's any way that I rename the new pod when k8s spawns up a new one? so I could grep for a specific keyword?
Note that I don't want to egrep something like firstpod-[0-9]-something
because that's just an example. A lot of pods have a lot of different names, that was just an example.
Thanks!
You need to label your deployment
somehow, for example we set label app: myapp
below:
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: nginx
spec:
template:
metadata:
labels:
app: my-app
spec:
containers:
- image: nginx
name: nginx
After that you can get deployment's pod name very easy:
POD=$(kubectl get pod -l app=my-app -o jsonpath="{.items[0].metadata.name}")
and execute some command there, for example:
kubectl exec -ti $POD -- uname -a