Running exec commands on a non-specific pod

3/17/2021

I havw a question, as part of the kubectl deployment process we currently run, we sometimes need to run migrations on the database as part of that process.

We do what we call a rollout restart after we have re-built a tagged Docker image.

However, we usually have anywhere between 2 and 4 pods, with randomly assigned names, e.g.:

web-7f54669b5f-c6z8m             1/1     Running   0          55s
web-7f54669b5f-fp2kw             1/1     Running   0          67s

To run, say, a database migration command, we could do:

kubectl exec --stdin --tty web-7f54669b5f-fp2kw -- python manage.py migrate --plan

That's fine. But we were wondering if there a way to just target any of the "web" pods ...?

I'm assuming it's not possible, but not 100% sure why...

-- Micheal J. Roberts
kubernetes

1 Answer

3/18/2021

So, what you can do is add unique labels to all pods and fetch each one of them using labels.

Example:

kubectl exec --stdin --tty $(kubectl get po -l "<label_name>=<label_value>" \
-o jsonpath='{.items[0].metadata.name}') -- python manage.py migrate --plan
-- Gautam Rajotya
Source: StackOverflow