Grep command to extract a kubernetes pod name

4/2/2020

I am currently working on a bash script to reduce the time it takes for me to build the db for a project. Currently I have several databases running in the same namespace and I want to extract only the specific pod name.

I run kubectl get pods

NAME                        READY   STATUS    RESTARTS   AGE
elastic                     1/1     Running   0          37h
mysql                       1/1     Running   0          37h

Now I want to save one of the pod names.

I'm currently running this foo=$(kubectl get pods | grep -e "mysql") and it returns mysql 1/1 Running 0 37h which is the expected results of the command. Now I just want to be able to extract the pod name as that variable so that I can pass it on at a later time.

-- John Baltes
bash
grep
kubernetes

3 Answers

4/2/2020

This should work for you

foo=$(kubectl get pods | awk '{print $1}' | grep -e "mysql")
-- DT.
Source: StackOverflow

4/3/2020

If I'm not mistaken, you merely needs to get only pod names to reuse these later.

The kubectl get --help provides a lot of good information on what you can achieve with just a kubectl without invoking the rest of the heavy artillery like awk, sed, etc.

List a single pod in JSON output format.

kubectl get -o json pod web-pod-13je7

List resource information in custom columns.

kubectl get pod test-pod -o custom-columns=CONTAINER:.spec.containers[0].name,IMAGE:.spec.containers[0].image

Return only the phase value of the specified pod. kubectl get -o template pod/web-pod-13je7 --template={{.status.phase}}

In this particular case I see at least 2 workarounds :

1) Custom columns. You can get virtually any output (and then you can grep/tr/awk if needed):

$ kubectl get pods --no-headers=true -o custom-columns=NAME_OF_MY_POD:.metadata.name

mmmysql-6fff9ffdbb-58x4b
mmmysql-6fff9ffdbb-72fj8
mmmysql-6fff9ffdbb-p76hx
mysql-tier2-86dbb787d9-r98qw
nginx-65f88748fd-s8mgc

2) jsonpath (the one @vault provided):

kubectl get pods -o=jsonpath='{.items..metadata.name}'

Hope that sheds light on options you have to choose from. Let us know if that helps.

-- Nick
Source: StackOverflow

4/2/2020

kubectl already allows you to extract only the names:

kubectl get pods -o=jsonpath='{.items..metadata.name}' | fgrep mysql
-- vault
Source: StackOverflow