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.
kubectl get nsdoesn't output JSON unless you add-o json. This:Should result in an error like:
kubectl get ns -o jsonemits a JSON response that contains a list ofNamespaceresources in theitemskey. You need to get themetadata.nameattribute 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 ourjqexpression:This will output your desired namespaces. At this point, there's no reason to store this in array and use a
forloop; you can just pipe the output toxargs: