Home > Enterprise >  How to exec a pod in kubernetes in a shell script if the pod name changes with every deployment
How to exec a pod in kubernetes in a shell script if the pod name changes with every deployment

Time:01-20

Same pods with every deployment get a different name so how to put this in shell scripts so that we can exec it to pods without changing the script with every deployment

deployed 1st time

NAMESPACE NAME READY

default call-f6f8cfd84-5l6zv 3/3

depolyed 2nd time

default call-7gcfrd45d-264df 3/3

tried multiple ways but not working

CodePudding user response:

You can exec into statefulset/deployment or other k8s workloads too. This will let you exec into the first pod deployed by the workload. The following example shows how to exec into the first pod deployed by the statefulset db-cluster in demo namespace in interactive mode using bash shell. I hope this helps!

kubectl exec -it -n demo sts/db-cluster -- bash

CodePudding user response:

You can use the Kubernetes kubectl command to dynamically retrieve the pod name based on certain criteria, such as the pod's label or the deployment's name.

Here are a few examples:

Get the pod name based on the deployment name:

pod_name=$(kubectl get pods -l pod=call -o jsonpath='{.items[0].metadata.name}')

This command retrieves the pod name of the first pod that has a label pod=call and assigns it to the variable pod_name.

Get the pod name based on the deployment name:

deployment_name=call
pod_name=$(kubectl get pods -l pod=${deployment_name} -o jsonpath='{.items[0].metadata.name}')

This command retrieves the pod name of the first pod that has a label pod=call and assigns it to the variable pod_name.

Get the pod name based on the namespace and deployment name:

namespace=default
deployment_name=call
pod_name=$(kubectl get pods -n ${namespace} -l pod=${deployment_name} -o jsonpath='{.items[0].metadata.name}')

This command retrieves the pod name of the first pod that has a label pod=call in the namespace default and assigns it to the variable pod_name.

Once you have the pod name in a variable, you can use it in your shell script to execute commands on that pod.

You can get the pod label name using command:

kubectl describe pod {pod_name}

The label will be same for every deployment changes.

Note that this approach retrieves the name of the first pod that matches the specified label and namespace, so it's assuming that you only have one pod with that label and namespace. If you have multiple pods that match the criteria, you'll need to find a way to select the specific pod you want to execute the command on.

  • Related