skip to Main Content

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


  1. 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
    
    Login or Signup to reply.
  2. kubectl get ns 
    

    output

    NAME                          STATUS        AGE
    default                       Active        75d
    kube-public                   Active        75d
    kube-system                   Active        75d
    oci-service-operator-system   Active        31d
    olm                           Active        31d
    

    command

    kubectl get ns --no-headers |  awk '{if ($1 ~ "de") print $1}'
    

    Output

    default
    kube-node-lease
    

    this will give you a list of namespaces

    array=$(kubectl get ns --no-headers |  awk '{if ($1 ~ "de") print $1}')
    

    Testing

    bash-4.2$ array=$(kubectl get ns --no-headers |  awk '{if ($1 ~ "de") print $1}')
    bash-4.2$ echo $array
    default kube-node-lease
    bash-4.2$ for n in $array; do echo $n; done
    default
    kube-node-lease
    bash-4.2$ 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search