如何使用jq解析“ kubectl get pods”的JSON格式输出并创建数组

时间:2018-11-02 15:26:36

标签: json kubernetes jq kubectl

运行此命令后,JSON输出返回给我

kubectl get pods -o json | jq '.items[].spec.containers[].env'

这是我的kuberntes集群上的

[
  {
    "name": "USER_NAME",
    "value": "USER_NAME_VALUE_A"
  },
  {
    "name": "USER_ADDRESS",
    "value": "USER_ADDRESS_VALUE_A"
  }
]
[
  {
    "name": "USER_NAME",
    "value": "USER_NAME_VALUE_B"
  },
  {
    "name": "USER_ADDRESS",
    "value": "USER_ADDRESS_VALUE_B"
  }
]

我想创建一个统一的数组/字典(使用 Bash 脚本),它类似于下面的示例,我如何获得每个键的值?

[
  {
    "USER_NAME": "USER_NAME_VALUE_A",
    "USER_ADDRESS": "USER_ADDRESS_VALUE_A"
  },
  {
    "USER_NAME": "USER_NAME_VALUE_B",
    "USER_ADDRESS": "USER_ADDRESS_VALUE_B"
  }
]

3 个答案:

答案 0 :(得分:1)

这将以bash的方式进行。您会惊讶于bash可以做什么:

#!/bin/bash

NAMES=`kubectl get pods -o=jsonpath='{range .items[*]}{.spec.containers[*].env[*].name}{"\n"}' | tr -d '\011\012\015'`
VALUES=`kubectl get pods -o=jsonpath='{range .items[*]}{.spec.containers[*].env[*].value}{"\n"}' | tr -d '\011\012\015'`

IFS=' ' read -ra NAMESA <<< "$NAMES"
IFS=' ' read -ra VALUESA <<< "$VALUES"

MAXINDEX=`expr ${#NAMESA[@]} - 1`

printf "[\n"
for i in "${!NAMESA[@]}"; do
  printf "  {\n"
  printf "  \"USER_NAME\": \"${NAMESA[$i]}\",\n"
  printf "  \"USER_ADDRESS\": \"${VALUESA[$i]}\"\n"
  if [ "$i" == "${MAXINDEX}" ]; then
    printf "  }\n"
  else
    printf "  },\n"
  fi
done
printf "]\n"

答案 1 :(得分:0)

使用jsonpath

C02W84XMHTD5:~ iahmad$ kubectl get pods --all-namespaces -o=jsonpath='{range .items[*]}{.metadata.name}{"\n"}'
coredns-c4cffd6dc-nsd2k
etcd-minikube
kube-addon-manager-minikube
kube-apiserver-minikube
kube-controller-manager-minikube
kube-dns-86f4d74b45-d5njm
kube-proxy-pg89s
kube-scheduler-minikube
kubernetes-dashboard-6f4cfc5d87-b7n7v
storage-provisioner
tiller-deploy-778f674bf5-vt4mj

https://kubernetes.io/docs/reference/kubectl/jsonpath/

它也可以输出键值

C02W84XMHTD5:~ iahmad$ kubectl get pods --all-namespaces -o=jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.startTime}{"\n"}{end}'
coredns-c4cffd6dc-nsd2k 2018-10-16T21:44:19Z
etcd-minikube   2018-10-29T17:30:56Z
kube-addon-manager-minikube 2018-10-29T17:30:56Z
kube-apiserver-minikube 2018-10-29T17:30:56Z
kube-controller-manager-minikube    2018-10-29T17:30:56Z
kube-dns-86f4d74b45-d5njm   2018-10-16T21:44:16Z
kube-proxy-pg89s    2018-10-29T17:32:05Z
kube-scheduler-minikube 2018-10-29T17:30:56Z
kubernetes-dashboard-6f4cfc5d87-b7n7v   2018-10-16T21:44:19Z
storage-provisioner 2018-10-16T21:44:19Z
tiller-deploy-778f674bf5-vt4mj  2018-11-01T13:45:23Z

然后您可以按空格将其拆分并形成json或列表

答案 2 :(得分:0)

当您使用 jq 作为过滤器时,为什么不也将其用作转换器?

kubectl get pods -o json | \
jq '.items|map(.spec.containers|map(.env|map({key: .name, value})|from_entries)|add)'

我知道这完全是一个死灵法师徽章,但仍然;)