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!
Run kubectl get deployments to check if the Deployment was created. When you inspect the Deployments in your cluster, the following fields are displayed: NAME lists the names of the Deployments in the namespace. READY displays how many replicas of the application are available to your users.
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
Like Nickolay wrote, use a label to help selecting. Then you can use
kubectl get pods -l app=my-app -o custom-columns=:metadata.name
This gets you the name of the pod that has the label "app=my-app"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With