Search code examples
bashshellkuberneteskubectl

How to call kubernetes pod name in a shell script?


I am writing a shell script for executing a pod for which the syntax is:

winpty  kubectl --kubeconfig="C:\kubeconfig" -n namespace exec -it podname bash

This works fine but since podname is not stable and changes for every deployment so is there any alternative for this?

Thanks.


Solution

  • You can use normally $ kubectl exec command but define value for changing pod name.

    Assuming that you have deployment and labeled pods: app=example, simply execute:

    $ kubectl exec -it $(kubectl get pods -l app=example -o custom-columns=:metadata.name) -- bash
    

    EDIT:

    You can also execute:

    POD_NAME = $(kubectl get pods -l app=example -o custom-columns=":metadata.name")
    

    or

    POD_NAME = $(kubectl get pods -l app=example -o jsonpath = "{. Items [0] .metadata.name}")
    

    finally

    $ winpty kubectl exec -ti $POD_NAME --bash
    

    Make sure that you execute command in proper namespace - you can also add -n flag and define it.