ProvoPropoli
ProvoPropoli

Reputation: 185

How to access a kubernetes pod by its partial name?

I often run tasks like:

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?

Upvotes: 5

Views: 5568

Answers (4)

koehn
koehn

Reputation: 804

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.

Upvotes: 2

Nahum
Nahum

Reputation: 7197

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

Upvotes: 2

acid_fuji
acid_fuji

Reputation: 6853

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.

Upvotes: 0

Aleksandr Erokhin
Aleksandr Erokhin

Reputation: 1982

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

Upvotes: 2

Related Questions