How to access a kubernetes pod by its partial name?

4/7/2020

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?

-- ProvoPropoli
kubectl
kubernetes

2 Answers

4/8/2020

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.

-- acid_fuji
Source: StackOverflow

4/7/2020

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/ .

-- Aleksandr Erokhin
Source: StackOverflow