Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kubectl get pods by container environment variable

Can I use kubectl get pods with some sort of field selector or selector that supports getting a single pod based upon a container environment variable?

I'd like to get this pod, and only this pod out of thousands and thousands, based upon the value of ENVIRONMENT_VARIABLE with kubectl.

apiVersion: v1
kind: Pod
metadata:
  name: my-pod
  namespace: default
spec:
  containers:
  - env:
    - name: ENVIRONMENT_VARIABLE
      value: abc123
    image: my-images
    imagePullPolicy: IfNotPresent
    name: my-pod

kubectl get pods --field-selector no, field is not supported

kubectl get pods -l it's not a label

What else can I try, if anything?

like image 517
duffn Avatar asked Sep 06 '25 03:09

duffn


1 Answers

I have a pod my-pod with an environment variable PORT with value 8080 like:

  metadata:
  ...
    name: my-pod
  ...
  spec:
    containers:
    - env:
      - name: PORT
        value: "8080"
  ...

and I can use kubectl to filter this pod like:

$ kubectl get pods --all-namespaces \
-o=jsonpath=\
'{range .items[*]}{.metadata.name}{"\t"}{.spec.containers[*].env[?(@.name=="PORT")]}{"\n"}{end}' | \
grep 8080

output is:

my-pod  map[name:PORT value:8080]

So, you can try:

kubectl get pods --all-namespaces \
-o=jsonpath=\
'{range .items[*]}{.metadata.name}{"\t"}{.spec.containers[*].env[?(@.name=="ENVIRONMENT_VARIABLE")]}{"\n"}{end}' | \
grep abc123
like image 100
Vikram Hosakote Avatar answered Sep 09 '25 18:09

Vikram Hosakote