JimmyLiao

JimmyLiao Notes: Developer, Runner, Thinker

Tips and Tricks: The usage of xargs for kubectl

2021-11-08 Kubernetes Linux

When performing the operation on the cluster, you may need to check/edit the pod or resource back and forth. Here is one of the useful linux command xargs to speed up your kubectl operation.

  1. You have to check the pod status by checking log, but the pod NAME may not be identical.

    $ kubectl -n hub get pod
    
    NAME                       READY   STATUS    RESTARTS   AGE
    primehub-bootstrap-c9dng   1/1     Running   0          21h
    
    $ kubectl -n hub logs primehub-bootstrap-c9dng
    ...
    

    so you can just use like:

    $ kubectl -n hub get pod --no-headers | cut -d' ' -f1 | xargs kubectl -n hub logs
    
    • kubectl has --no-headers option to output without header column
    • cut -d' ' -f to get the first column after trimming spaces
    • the last pipeline pass xargs strings X to the kubectl -n hub logs X last parameter
  2. You may have several Custom Resources, would like to delete them all.

    $ kubectl get crd | grep primehub | cut -d' ' -f1 | xargs kubectl delete crd
    
    customresourcedefinition.apiextensions.k8s.io "datasets.primehub.io" deleted
    customresourcedefinition.apiextensions.k8s.io "images.primehub.io" deleted
    customresourcedefinition.apiextensions.k8s.io "instancetypes.primehub.io" deleted
    
  3. You want to dump the pod which is not Running/Completed.

    $ kubectl -n kube-system get pod --no-headers | grep -v -e Running -e Completed | cut -d' ' -f1 | xargs -I {} bash -c 'kubectl -n kube-system get pod {} -o yaml > {}.yaml'
    
    • grep -v for inverse-match, -e for pattern
    • bash -c means the commands are read from string
comments powered by Disqus