How to access a kubernetes pod by its partial name?

Viewed 2194

I often run tasks like:

  • Read the log of the service X or
  • Attach a shell inside the service Y

I always use something in my history like:

kubectl logs `kubectl get pods --no-headers -o custom-columns=":metadata.name" | grep <partial_name>`

or

kubectl exec -it `kubectl get pods --no-headers -o custom-columns=":metadata.name" | grep <partial_name>` bash

Do you know if kubectl has already something in place for this? Or should I create my own set of aliases?

4 Answers

Kubernetes instances are loosely coupled by the means of labels (key-value pairs). Because of that Kubernetes provides various functionalities that can help you to operate on sets of objects based on labels.

In case you have several pods of the same service good chances that they are managed by some ReplicaSet with the use of some specific label. You should see it if you run:

kubectl get pods --show-labels

Now for aggregating logs for instance you could use label selector like:

kubectl logs -l key=value

For more info please see: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/ .

You can enable shell autocompletion. Kubectl provides this support for Bash and Zsh which will save you a lot of typing (you will use TAB to get the suggestion/completion).

Kuberentes documentations has a great set of information about how to enable autocompletion under Optional kubectl configurations. It covers Bash on Linux, Bash on MacOS and Zsh.

added to my .zshconfig

sshpod () {
  kubectl exec --stdin --tty `kubectl get pods --no-headers -o custom-columns=":metadata.name" | grep ${1} | head -n 1` -- /bin/bash
}

usage

sshpod podname

this

  1. finds all pods
  2. greps needed name
  3. picks the first
  4. sshs into the pod

You can go access a pod by its deployment/service/etc:

kubectl exec -it svc/foo -- bash
kubectl exec -it deployment/bar -- bash

Kubernetes will pick a pod that matches the criteria and send you to it.

Related