How can I delete all pods of specific deployments of specific namespaces?

9/24/2019

I am looking for a way to delete all pods of specific deployments of specific namespaces. In other words, given:

x - list of namespaces
y - list of deployments

for i in x:
  for j in y:
    delete all pods of deployment j in namespace i

I would be happy if someone knows how to do it in bash commands.

Thanks!

-- Yosi Karl
bash
kubernetes

4 Answers

9/24/2019

I believe something like this will do it:

#!/bin/bash

NAMESPACES=( n1 n2 n3 )
DEPLOYMENTS=( dep1 dep2 dep3 )

for i in "${NAMESPACES[@]}"
do
  for x in "${DEPLOYMENTS[@]}"
  do
     # Get the pods in the deployment
     PODS=$(kubectl -n $i get pods --no-headers | awk '{print $1}' | grep $x | tr '\n' ' ')
     kubectl -n $i delete pods $PODS
  done
done
-- Rico
Source: StackOverflow

9/24/2019

Generally you do this with label selectors. You would put something in the template metadata like labels: {app: foo} and then kubectl delete pod --all-namespaces -l app=foo.

-- coderanger
Source: StackOverflow

9/24/2019

If you want "single line" solution you can use bash's braces expansion together with Kubernetes' Labels and Selectors:

eval 'kubectl delete pods --namespace='{n1,n2,n3}' --selector='{app=foo1,app=foo2,svc=svc1,svc=svc2}';'

Another way to write that:

eval 'kubectl delete pods -n '{n1,n2,n3}' -l '{"'app in (foo1,foo2)'","'svc in (svc1,svc2)'"}';'
-- victortv
Source: StackOverflow

9/25/2019

You've explained in comments that your use case is for your Pods to pick up new data from ConfigMaps. For this purpose, you do not need to directly delete any Pods.

If your Pods get data from ConfigMaps via a mounted volume, and you're not using the subPath feature, then ConfigMap changes get picked up automatically and you don't need to do anything to your Deployments or Pods (you might have to wait a minute or so for the change to propagate). For this to work, of course, your application within your Pod needs to watch for changes to the mounted files and incorporate them when changes appear.

If, on the other hand, your Pods are extracting values via, say, environment variables, then you simply need to restart your Deployments, for which there is a more convenient kubectl command than deletion, in fact you don't need to muck around directly with Pods at all. Use kubectl rollout restart:

namespaces="ns1 ns2"
deployments="dep1 dep2"

for ns in ${namespaces}; do
  for dep in ${deployments}; do
    kubectl rollout restart deployment/"${dep}" --namespace="${ns}"
  done
done
-- Amit Kumar Gupta
Source: StackOverflow