Execute a command on a pod of a deployment with a single command

hacking k8s kubernetes bash

TL;DR

kubectl exec -it $(kubectl get pods -o name | grep -m1 INSERT_DEPLOYMENT_NAME_HERE | cut -d'/' -f 2) INSERT_YOUR_COMMAND_HERE  

Motivation

When I want to run execute a command on a pod of a deployment, I usually have to search for the name of the pod generated by a deployment (or replica controller) by

kubectl get po  

Then look by my eye or use control + F to find the pod I want then run

kubectl exec -it INSERT_POD_NAME_HERE /bin/bash  

It is acceptable when you don't have many pods/deployment and you rarely need to execute a command on a pod. Otherwise, it is a boring and time-consuming procedure.

Make it better

First, I can find the pod I want much faster by

kubectl get po | grep INSERT_DEPLOYMENT_NAME_HERE  

The returned result will contain only pods belonging to the INSERT_DEPLOYMENT_NAME_HERE deployment then you just need to pick the first one to execute by the above command.

Make it even better

Ok, I will combine into one-line command only

kubectl exec -it $(kubectl get pods -o name | grep -m1 INSERT_DEPLOYMENT_NAME_HERE | cut -d'/' -f 2) INSERT_YOUR_COMMAND_HERE  

For example:

kubectl exec -it $(kubectl get pods -o name | grep -m1 backend | cut -d'/' -f 2) "node scripts/db/migrates.js"