Search code examples
arraysbashkuberneteskubernetes-namespace

How can I get the names of all namespaces containing the word "nginx" and store those names in an array


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.


Solution

  • kubectl get ns doesn't output JSON unless you add -o json. This:

    array=($(kubectl get ns | jq -r 'keys[]'))
    

    Should result in an error like:

    parse error: Invalid numeric literal at line 1, column 5
    

    kubectl get ns -o json emits a JSON response that contains a list of Namespace resources in the items key. You need to get the metadata.name attribute from each item, so:

    kubectl get ns -o json | jq -r  '.items[].metadata.name'
    

    You only want namespaces that contain the word "nginx". We could filter the above list with grep, or we could add that condition to our jq expression:

    kubectl get ns -o json | jq -r  '.items[]|select(.metadata.name|test("nginx"))|.metadata.name'
    

    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 to xargs:

    kubectl get ns -o json |
    jq -r  '.items[]|select(.metadata.name|test("nginx"))|.metadata.name' |
    xargs kubectl delete ns