Albert
Albert

Reputation: 311

Get specific Kubernetes pods

I have the following list of pods:

user@compute:~> kubectl get pods -n test --template '{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}'
test-1
test-2
test-3
abc
cdf
dfg

I would like to get just the pods which includes test in the name. Is any way to accomplish that without using grep or for, but using template or any Kubernetes way of doing it?

Thank you

Upvotes: 0

Views: 1745

Answers (1)

acid_fuji
acid_fuji

Reputation: 6853

The majority of Kubernetes maintainers (as of now), does not intend to make kubectl command more advanced than external tools made especially for data set parsing (e.g. grep, jq), and suggest still to use external tools in use case similar to yours. There is a PR planned for making this limitation more visible in Docs for end-users.

Replacing output format from --template (go-template format) to --jsonpath would make theoretically possible to achieve your goal. But as it happens regex filter is not supported, and such a command results in following error:

error: error parsing jsonpath {.items[?(@.metadata.name=~/^test$/)].metadata.name}, unrecognized character in action: U+007E '~'

You check and follow the issue discussed here: https://github.com/kubernetes/kubernetes/issues/72220

Having said that, for now you you can give a try with jq instead grep command:

k get po -n monitoring -o json | jq '.items[] | select(.metadata.name|test("prom"))| .metadata.name'

 
"prometheus-k8s-0"
"prometheus-k8s-1"
"prometheus-operator-65c77bdd6c-lmrlf"

or use the only known to me workaround to achieve similar result w/o grep, use this very unattractive command:

 k set env po/prometheus-k8s-0 -n monitoring -c prometheus-config* --dry-run=client --list
# Pod prometheus-k8s-0, container prometheus-config-reloader
# POD_NAME from field path metadata.name

*this command uses the fact that '-c' accept wildcards, moreover I'm assuming that container names are consistent with Pod names

Upvotes: 2

Related Questions