JSONPath range not working when using kubectl

3/1/2019

I'm accessing Kubernetes through the CLI tool kubectl and I'm trying to get a list of all context names, one per line.

I know that JSONPath can be used to extract and format specific output. I get really close to what I want with

kubectl config view -o=jsonpath="{.contexts[*].name}"

but this puts all the names on the same line. I'm trying to use range to list all names separated by newlines:

kubectl config view -o=jsonpath='{range .contexts[*]}{.name}{"\n"}{end}'

But this just gives me an error:

error: unexpected arguments: [.contexts[*]}{.name}{"\n"}{end}]
See 'kubectl config view -h' for help and examples.

I've reviewed the kubectl documentation and what I'm doing is really similar to https://kubernetes.io/docs/tasks/access-application-cluster/list-all-running-container-images/#list-containers-by-pod, where the command is

kubectl get pods --all-namespaces -o=jsonpath='{range .items[*]}{"\n"}{.metadata.name}{":\t"}{range .spec.containers[*]}{.image}{", "}{end}{end}' |\
sort

but I can't see where I'm going wrong.

-- Axesilo
jsonpath
kubectl
kubernetes

2 Answers

3/1/2019

Your command works for me in kubectl 1.9.2

If it still doesn't work, you can use tr in bash to replace spaces with new lines:

kubectl config view -o=jsonpath="{.contexts[*].name}" | tr " " "\n" 
-- Amityo
Source: StackOverflow

3/1/2019

I figured it out. I had been using @ahmetb's kubectl-aliases script, which works fine with no problem, but one of the suggestions in the README was:

Print the full command before running it: Add this to your .bashrc or .zshrc file:

function kubectl() { echo "+ kubectl $@"; command kubectl $@; }

I had that function declaration in my .bashrc and it was stripping off the quotes for my jsonpath argument. As soon as I commented out that declaration and opened a new shell, the command worked correctly.

-- Axesilo
Source: StackOverflow