Search code examples
bashkuberneteskubectl

How to delete kubernetes resources across all namespaces?


I want to know if there is a way to delete specific resources in kubernetes across all namespaces? I want to delete all the services as type of LoadBalancer at once, and have this automated in a pipeline. I already built a xargs kubectl command which will get the name of LoadBalancer services across all namespaces and feed the output to the kubectl delete command. I just need to loop across all namespaces now.

kubectl get service -A -o json | jq '.items[] | select (.spec.type=="LoadBalancer")' | jq '.metadata.name' | xargs kubectl delete services --all-namespaces
error: a resource cannot be retrieved by name across all namespaces

If I remove the --all-namespaces flag and run --dry-run=client flag instead, then I get a dry-run deletion of all the services I want getting deleted on all namespaces. Is there a way k8s lets you delete resources by name across all namespaces?

Any ideas?

UPDATE: This is the output of running the command using --dry-run flag, it gets the name of all the services I want to delete and automatically feeds them to the kubectl delete command

kubectl get service -A -o json | jq '.items[] | select (.spec.type=="LoadBalancer")' | jq '.metadata.name' | xargs kubectl delete services --dry-run=client
service "foo-example-service-1" deleted (dry run)
service "bar-example-service-2" deleted (dry run)
service "baz-example-service-3" deleted (dry run)
service "nlb-sample-service" deleted (dry run)

The only part missing is that I need to do the deletion across all namespaces to delete all the specified services, I only want to delete services of type LoadBalancer and not other types of services like ClusterIP or NodePort or anything so the specific names must be provided.


Solution

  • You can achieve that using jsonpath with the following command:

    kubectl delete services $(kubectl get services --all-namespaces \
    -o jsonpath='{range .items[?(@.spec.type=="LoadBalancer")]}{.metadata.name}{" -n "}{.metadata.namespace}{"\n"}{end}')
    

    The output of the kubectl get command gives a list of <service_name> -n <namespace_name> strings that are used by the kubectl delete command to delete services in the specified namespaces.