kubectl get pods by container environment variable

2/7/2020

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?

-- duffn
kubectl
kubernetes

2 Answers

2/9/2020

via jq...

By name

kubectl get pods --all-namespaces --chunk-size=0 -o json | \
  jq '.items[] | select(.spec.containers[].env[]?.name == "ENVNAME")
               | .metadata.name'

By value

kubectl get pods --all-namespaces --chunk-size=0 -o json | \
  jq '.items[] | select(.spec.containers[].env[]?.value == "AVALUE")
               | .metadata.name'

By name and value

kubectl get pods --all-namespaces --chunk-size=0 -o json | \
  jq '.items[] | select(.spec.containers[].env[]? | .name == "ENVNAME" and .value == "AVALUE")
               | .metadata.name'

Or there's API client libraries for most languages. If you add --v=9 to a kubectl command it will output the endpoints it is hitting to gather data. In this case: https://api-server/api/v1/pods

-- Matt
Source: StackOverflow

2/7/2020

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
-- Vikram Hosakote
Source: StackOverflow