Home > Software engineering >  Output from kubectl images into an array (bash script)
Output from kubectl images into an array (bash script)

Time:02-17

I'm following the format of this stackoverflow post to try and get the jsonpath for images (for all pods) into an array, which I can then loop through and run a gcloud command on each item from the array.

The command I'm trying is:

array=( $(kubectl get pods -o jsonpath="{.items[*].spec.containers[*].image}" | jq -r 'keys[]') )
declare -p array

However I receive the error: parse error: Invalid numeric literal at line 1, column 41

When i run the command without the jq the command it's putting everything into the first index item, so a big long string, with spaces e.g.

typeset -a array=( 'eu.gcr.io/repo/imagename1 eu.gcr.io/repo/imagename2 eu.gcr.io/repo/imagename3 eu.gcr.io/repo/imagename4' )

Any ideas how I can get this output into separate array items and something I can use to iterate through?

CodePudding user response:

Your -o jsonpath="{.items[*].spec.containers[*].image}" outputs all of the image names on one line (here's mine):

nginx docker.local/node-server:1640867594 docker.local/node-server:1640867594 docker.local/node-server:1640867594 nginx nginx nginx nginx nginx

It's no longer JSON, so piping it into jq is going to do weird things. In your case, jq is (probably) complaining about one of the : items. In my case, I get a slightly different parse error.

Either drop the use of jq, or lean into it fully:

kubectl get pods -o json | jq -r '.items[].spec.containers[].image' | sort | uniq | ...
  • Related