Basically I want to automate this task where I have some namespaces in Kubernetes I need to delete and others that I want to leave alone. These namespaces contain the word nginx. So I was thinking in order to do that I could get the output of get namespace using some regex and store those namespaces in an array, then iterate through that array deleting them one by one.
array=($(kubectl get ns | jq -r 'keys[]'))
declare -p array
for n in {array};
do
kubectl delete $n
done
I tried doing something like this but this is very basic and doesn’t even have the regex. But I just left it here as an example to show what I’m trying to achieve. Any help is appreciated and thanks in advance.
2
Answers
kubectl get ns
doesn’t output JSON unless you add-o json
. This:Should result in an error like:
kubectl get ns -o json
emits a JSON response that contains a list ofNamespace
resources in theitems
key. You need to get themetadata.name
attribute from each item, so:You only want namespaces that contain the word "nginx". We could filter the above list with
grep
, or we could add that condition to ourjq
expression:This will output your desired namespaces. At this point, there’s no reason to store this in array and use a
for
loop; you can just pipe the output toxargs
:output
command
Output
this will give you a list of namespaces
Testing