How to list deployments having specific environment variables

1/10/2022

I would love to list deployments having mongodb environment value along with their phase status. Is there anyway to do so?

With this command, I get the deployments name which carries a specific environment value

kubectl get deploy -o=custom-columns="NAME:.metadata.name,SEC:.spec.template.spec.containers[*].env[*].value" | grep mongodb | cut -f 1 -d ' '

Output:

app1
app2
app3
app4

Output I want to get:

NAME                                     READY   UP-TO-DATE   AVAILABLE   AGE
app1                                     1/1     1            1           125d
app2                                     1/1     1            1           248d
app3                                     1/1     1            1           248d
app4                                     1/1     1            1           248d

Or it can be pods as well. I'd appreciate your help.

Thank you!

-- titanic
kubectl
kubernetes

1 Answer

1/11/2022

I had a go at a solution using kubectl but was unsuccessful.

I suspect (!?) you'll need to use additional tools to parse|process the results to get what you want. Perhaps using jq?

For Deployments, you can filter the results based on environment variable names using, e.g.:

FILTER="{.items[*].spec.template.spec.containers[*].env[?(@.name==\"mongodb\")]}"

kubectl get deployments \
--namespace=${NAMESPACE} \
--output=jsonpath="${FILTER}"

But this only returns the filtered path (i.e. items[*].spec.template.spec.containers[*].env).

With JSONPath, you ought (!) be able to apply the filter to the item but I this isn't supported (by kubectl's implementation) i.e.:

FILTER="{.items[?(@.spec.template.spec.containers[?(@.env[?(@.name==\"mongodb\")])])]}"

With jq, I think you'll be able to select the env.name, return the item's status and get the raw status values that you need. Something like:

FILTER='
.items[]
|select(.spec.template.spec.containers[].env[].name == "mongodb")
|{"name":.metadata.name, "ready":.status.readyReplicas}
'

kubectl get deployments \
--output=json \
| jq -r "${FILTER}"
-- DazWilkin
Source: StackOverflow