DEV Community

loading...

How to Restart All Pods in a Kubernetes Namespace

wagslane profile image Lane Wagner Originally published at qvault.io on ・2 min read

How To Restart All Pods in a Kubernetes Namespace

The post How to Restart All Pods in a Kubernetes Namespace first appeared on Qvault.

Where I work we use a repo-per-namespace setup and so it is often the case that I want to restart all the pods and deployments in a single Kubernetes namespace. Maybe I want to see the startup logs, maybe I want to take down production for a few seconds, don’t question my motivations.

Anyhow, what does matter is that bouncing all the deployments one-by-one is really obnoxious and I don’t like typing. In true developer laziness fashion I wrote a little script that will do it for me:

deploys=`kubectl -n $1 get deployments | tail -n +2 | cut -d ' ' -f 1`
for deploy in $deploys; do
  kubectl -n $1 rollout restart deployments/$deploy
done
Enter fullscreen mode Exit fullscreen mode

The usage is fairly simple, assuming we named the file kubebounce.sh

./kubebounce.sh {NAMESPACE}
Enter fullscreen mode Exit fullscreen mode

I made a little open-source repo with installation instructions if you want to add it to your $PATH. Be sure to star the repo if you find it useful.

How It Works

Bash isn’t exactly the easiest language to read. Let’s go over each portion of the script.

deploys=`kubectl -n $1 get deployments | tail -n +2 | cut -d ' ' -f 1`

Enter fullscreen mode Exit fullscreen mode

In bash, $1 refers to the first command-line argument, the namespace in our case. In essence, this line gets all the deployments in the target namespaces and saves them into a deploys variable. We pipe the output of the kubectl get deployments command into a tail -n +2 command, which just strips of the first line of the output. Then we run that output through a cut command which leaves us with a nice list of all the deployment names.

That’s actually the trickier part, next we just loop over all the deployments and restart them one-by-one:

for deploy in $deploys; do
  kubectl -n $1 rollout restart deployments/$deploy
done
Enter fullscreen mode Exit fullscreen mode

Thanks For Reading!

Follow us on Twitter @q_vault if you have any questions or comments

Take some coding courses on our new platform

Subscribe to our Newsletter for more programming articles

Discussion (0)

Forem Open with the Forem app