JSONPATH filtering

Hi,

I’ve gone through the CKA practice exam on KodeKloud and have started to go through KillerCoda exams. There is a question:

you have a script named svc-filter.sh . Update this script to include a command that filters and displays the value of target port of a service named redis-service using jsonpath only.

It should be in the format kubectl get svc OR It should be in the format kubectl get service

so I’m doing either:

kubectl get svc -o=jsonpath="{.items[?(@.metadata.name=='redis-service')].spec.ports[0].targetPort}"

or

kubectl get service redis-service -o=jsonpath="{.spec.ports[*].targetPort}"

but both give me an error.
Any idea that should be used here?

Ok, so it turns out there is a list with answer tied to this questionary and the right answer is

kubectl get svc redis-service -o jsonpath='{.spec.ports[0].targetPort}'

Means there is no equals sign in the command.
Frustrating.

You were over thinking the question.

kubectl get svc -o=jsonpath="{.items[?(@.metadata.name=='redis-service')].spec.ports[0].targetPort}"

No need to use a query to select the service by name from all the services, so you moved on to

kubectl get service redis-service -o=jsonpath="{.spec.ports[*].targetPort}"

Whilst this does work, if there were multiple ports defined it would get them all. Questions in CKA are not normally that involved.

Third answer is what was expected. Not sure what you mean by “there is no equals sign in the command”

I would go about solving such questions by doing

kubectl get service redis-service -o yaml

and then building the jsonpath expression from what is seen in the output.

I also over though the question as simple solutions failed

  1. I added two spaces before the -o argument
  2. i enclosed the quotes around the jsonpath

Example:

kubectl get svc redis-service  -o 'jsonpath={ .spec.ports[0].targetPort }' #wrong: too much spaces + quotes around jsonpath
kubectl get svc redis-service  -o 'jsonpath={ .spec.ports[*].targetPort }' #wrong: too much spaces
kubectl get svc redis-service  -o 'jsonpath={.spec.ports[0].targetPort}' # two spaces before -o
kubectl get svc redis-service  -o jsonpath='{.spec.ports[0].targetPort}' # two spaces before -o
kubectl get svc redis-service  -o jsonpath="{.spec.ports[0].targetPort}" # two spaces before -o

The number of spaces before or after -o does not matter as long as it is at least one.

What needs to be quoted is the jsonpath expression, not the word jsonpath

Note this is not about some weirdness of kubectl. It is about how bash processes the command line arguments before giving them to kubectl. { and } have special meaning to bash, therefore to pass them unfettered to kubectl we have to quote the expression.