k8s解析数据 -o=jsonpath=‘{}‘ 的使用

kubectl -o=jsonpath= 是 Kubernetes 命令行工具 kubectl 中的一个输出选项,用于以 JSONPath 格式提取并展示 API 对象的部分内容。JSONPath 是一种查询语言,它允许用户在 JSON 结构中导航和提取数据。这对于自动化脚本和快速查询 Kubernetes 资源的特定部分非常有用。

当你执行 kubectl 命令并使用 -o--output 标志时,可以指定输出格式。如果后面跟的是 jsonpath= ,那么你就可以提供一个 JSONPath 表达式来精确地选择你想要从资源描述中提取的信息。

基本语法结构如下:

kubectl [command] [resource] [-o=jsonpath='{expression}']

这里的 expression 是一个遵循 JSONPath 语法的字符串,用于指定要提取的数据路径。例如:

  • {.metadata.name} 会提取对象的名称。
  • {.spec.containers[*].name} 会提取所有容器的名称,如果有多个容器的话。
  • {range .spec.containers[*]}{.name}{"\n"}{end} 使用 range 来迭代每个容器,并打印它们的名称,每个名称后跟一个换行符。

JSONPath 表达式中常用的符号包括:

  • . 访问对象的属性。
  • [] 访问数组元素或作为筛选条件。
  • {} 定义表达式或者用于创建输出模板。
  • * 通配符,匹配数组中的所有元素。
  • @ 引用当前对象。

通过这种方式,kubectl -o=jsonpath= 提供了一种灵活且强大的方法来查看 Kubernetes 资源的定制化视图。

示例如下:

kubectl get pod  csi-attacher-lxcfsplugin-0 -o yaml
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: "2024-04-17T06:33:35Z"
  generateName: csi-attacher-lxcfsplugin-
  labels:
    app: csi-attacher-lxcfsplugin
    controller-revision-hash: csi-attacher-lxcfsplugin-75c7658464
    statefulset.kubernetes.io/pod-name: csi-attacher-lxcfsplugin-0
  name: csi-attacher-lxcfsplugin-0
  namespace: lxcfs-csi
  ownerReferences:
  - apiVersion: apps/v1
    blockOwnerDeletion: true
    controller: true
    kind: StatefulSet
    name: csi-attacher-lxcfsplugin
    uid: c520c298-7c0f-40c5-9878-8ea47be81e4a
  resourceVersion: "34427971"
  uid: b64b595e-c2a5-49c8-8ef2-a9b9987b2fe3
spec:
  containers:
  - args:
    - --csi-address=$(ADDRESS)
    - --v=5
    env:
    - name: ADDRESS
      value: /var/lib/csi/sockets/pluginproxy/csi.sock
    image: docker.io/lxcfs:v1
    imagePullPolicy: Never
    name: csi-provisioner
    resources:
      limits:
        cpu: 150m
        memory: 100Mi
      requests:
        cpu: 150m
        memory: 100Mi
    terminationMessagePath: /dev/termination-log
    terminationMessagePolicy: File
    volumeMounts:
    - mountPath: /var/lib/csi/sockets/pluginproxy
      name: socket-dir
    - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
      name: kube-api-access-xsjrp
      readOnly: true
  - args:
    - --v=5
    - --csi-address=$(ADDRESS)
    env:
    - name: ADDRESS
      value: /var/lib/csi/sockets/pluginproxy/csi.sock
    image: docker.io/lxcfs:v1
    imagePullPolicy: Never
    name: csi-attacher
    resources:
      limits:
        cpu: 150m
        memory: 100Mi
      requests:
        cpu: 150m
        memory: 100Mi
    terminationMessagePath: /dev/termination-log
    terminationMessagePolicy: File
    volumeMounts:
    - mountPath: /var/lib/csi/sockets/pluginproxy/
      name: socket-dir
    - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
      name: kube-api-access-xsjrp
      readOnly: true
  - args:
    - --nodeid=$(NODE_ID)
    - --endpoint=$(CSI_ENDPOINT)
    - --log-retain-date=5
    - --log-compress
    - --log-file-path=/var/log/controller.log
    - --log-max-size=200
    - --log-max-backups=10
    command:
    - /csi-server
    env:
    - name: NODE_ID
      valueFrom:
        fieldRef:
          apiVersion: v1
          fieldPath: spec.nodeName
    - name: CSI_ENDPOINT
      value: unix://plugin/csi.sock
    image: docker.io/lxcfs:v1
    imagePullPolicy: Never
    name: csi-server
    resources:
      limits:
        cpu: 150m
        memory: 100Mi
      requests:
        cpu: 150m
        memory: 100Mi
    terminationMessagePath: /dev/termination-log
    terminationMessagePolicy: File
    volumeMounts:
    - mountPath: /plugin
      name: socket-dir
    - mountPath: /var/log
      name: log-volume
    - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
      name: kube-api-access-xsjrp
      readOnly: true
  - args:
    - /liveness/csi-livenessprobe --csiAddress=/var/lib/kubelet/plugins/csi-lxcfsplugin/csi.sock
      --httpEndpoint=127.0.0.1:10926
    command:
    - /bin/sh
    - -c
    image: docker.io/lxcfs:v1
    imagePullPolicy: Never
    name: health-check
    resources:
      limits:
        cpu: 10m
        memory: 100M
      requests:
        cpu: 10m
        memory: 100M
    terminationMessagePath: /dev/termination-log
    terminationMessagePolicy: File
    volumeMounts:
    - mountPath: /plugin/
      name: socket-dir
    - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
      name: kube-api-access-xsjrp
      readOnly: true
  dnsPolicy: ClusterFirst
  enableServiceLinks: true
  hostname: csi-attacher-lxcfsplugin-0
  nodeName: docker123
  nodeSelector:
    node-role.kubernetes.io/master: ""
  preemptionPolicy: PreemptLowerPriority
  priority: 1000000000
  priorityClassName: lxcfs-csi-priority-class
  restartPolicy: Always
  schedulerName: default-scheduler
  securityContext: {}
  serviceAccount: csi-attacher
  serviceAccountName: csi-attacher
  subdomain: csi-attacher
  terminationGracePeriodSeconds: 30
  tolerations:
  - operator: Exists
  volumes:
  - emptyDir: {}
    name: socket-dir
  - hostPath:
      path: /var/lib/docker/logs/lxcfs-csi-server
      type: DirectoryOrCreate
    name: log-volume
  - name: kube-api-access-xsjrp
    projected:
      defaultMode: 420
      sources:
      - serviceAccountToken:
          expirationSeconds: 3607
          path: token
      - configMap:
          items:
          - key: ca.crt
            path: ca.crt
          name: kube-root-ca.crt
      - downwardAPI:
          items:
          - fieldRef:
              apiVersion: v1
              fieldPath: metadata.namespace
            path: namespace
status:
  conditions:
  - lastProbeTime: null
    lastTransitionTime: "2024-04-17T06:33:35Z"
    status: "True"
    type: Initialized
  - lastProbeTime: null
    lastTransitionTime: "2024-04-22T02:26:11Z"
    status: "True"
    type: Ready
  - lastProbeTime: null
    lastTransitionTime: "2024-04-22T02:26:11Z"
    status: "True"
    type: ContainersReady
  - lastProbeTime: null
    lastTransitionTime: "2024-04-17T06:33:35Z"
    status: "True"
    type: PodScheduled
  containerStatuses:
  - containerID: containerd://3c0eeb141059a8dc099c1d3c4c98a6a6f25b855335b319a240f167983b5c00f4
    image: docker.io/lxcfs:v1
    imageID: sha256:19ec336305e47bfd0f64a7d1eb17dc01cb67cbbb856dbf18307999208c70c80b
    lastState: {}
    name: csi-attacher
    ready: true
    restartCount: 0
    started: true
    state:
      running:
        startedAt: "2024-04-22T02:25:41Z"
  - containerID: containerd://aa0dd18c42e1e6ecade723a358856e8705cf20ebc418290e74ec0c76325fd78a
    image: docker.io/lxcfs:v1
    imageID: sha256:1011f81cb57bccc5591e54874ca3a16e0b20a8f80765ee2bab2eb55d3782e84e
    lastState: {}
    name: csi-provisioner
    ready: true
    restartCount: 0
    started: true
    state:
      running:
        startedAt: "2024-04-22T02:25:41Z"
  - containerID: containerd://23465fdf825016cefb4982c3367d9e34839f60707e2ecb57b4b6e617d3b341e0
    image: docker.io/lxcfs:v1
    imageID: sha256:e28f1150ab6c9bcf294be21403faf6862ad460891408a628ac23102d5f29b61d
    lastState: {}
    name: csi-server
    ready: true
    restartCount: 0
    started: true
    state:
      running:
        startedAt: "2024-04-22T02:25:56Z"
  - containerID: containerd://116a11be9a0b548bd04589c59228702043f0d3b1dad39a11f25f1aa1d68378be
    image: docker.io/lxcfs:v1
    imageID: sha256:f9cf76b861fe4ba215a07ac5851d43aea7247996490992e38176e51ada755dd3
    lastState: {}
    name: health-check
    ready: true
    restartCount: 0
    started: true
    state:
      running:
        startedAt: "2024-04-22T02:26:11Z"
  hostIP: 11.166.91.187
  phase: Running
  podIP: 10.244.0.54
  podIPs:
  - ip: 10.244.0.54
  qosClass: Guaranteed
  startTime: "2024-04-17T06:33:35Z"

1、获取kind

$ kubectl get pod  csi-attacher-lxcfsplugin-0 -o=jsonpath='{.kind}'
Pod

2、获取metadata 中的 generateName

$ kubectl get pod  csi-attacher-lxcfsplugin-0 -o=jsonpath='{.metadata.generateName}'
csi-attacher-lxcfsplugin-

3、获取metadata 中的labels中的app

$ kubectl get pod  csi-attacher-lxcfsplugin-0 -o=jsonpath='{.metadata.labels.app}'
csi-attacher-lxcfsplugin

4、获取metadata 中的ownerReferences中的uid

$ kubectl get pod  csi-attacher-lxcfsplugin-0 -o=jsonpath='{.metadata.ownerReferences}'
[{"apiVersion":"apps/v1","blockOwnerDeletion":true,"controller":true,"kind":"StatefulSet","name":"csi-attacher-lxcfsplugin","uid":"c520c298-7c0f-40c5-9878-8ea47be81e4a"}]
# 得到一个列表,且列表中只有一个值
$ kubectl get pod  csi-attacher-lxcfsplugin-0 -o=jsonpath='{.metadata.ownerReferences[0].uid}'
c520c298-7c0f-40c5-9878-8ea47be81e4a

5、获取spec 第四个containers中的resources中的requests中的cpu

$ kubectl get pod  csi-attacher-lxcfsplugin-0 -o=jsonpath='{.spec.containers[3]}' 
{"args":["/liveness/csi-livenessprobe --csiAddress=/var/lib/kubelet/plugins/csi-lxcfsplugin/csi.sock --httpEndpoint=127.0.0.1:10926"],"command":["/bin/sh","-c"],"image":"reg.docker.alibaba-inc.com/alibaba_apsara_paas/lxcfs_csi_livenessprobe:unionbase-v1","imagePullPolicy":"Never","name":"health-check","resources":{"limits":{"cpu":"10m","memory":"100M"},"requests":{"cpu":"10m","memory":"100M"}},"terminationMessagePath":"/dev/termination-log","terminationMessagePolicy":"File","volumeMounts":[{"mountPath":"/plugin/","name":"socket-dir"},{"mountPath":"/var/run/secrets/kubernetes.io/serviceaccount","name":"kube-api-access-xsjrp","readOnly":true}]}

$ kubectl get pod  csi-attacher-lxcfsplugin-0 -o=jsonpath='{.spec.containers[3].resources}' 
{"limits":{"cpu":"10m","memory":"100M"},"requests":{"cpu":"10m","memory":"100M"}}

$ kubectl get pod  csi-attacher-lxcfsplugin-0 -o=jsonpath='{.spec.containers[3].resources.requests}' 
{"cpu":"10m","memory":"100M"}

$ kubectl get pod  csi-attacher-lxcfsplugin-0 -o=jsonpath='{.spec.containers[3].resources.requests.cpu}' 
10m

6、获取每一个容器的name

$ kubectl get pod  csi-attacher-lxcfsplugin-0 -o=jsonpath='{range .spec.containers[*]}{.name}{"\n"}{end}' 
csi-provisioner
csi-attacher
csi-server
health-check
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 `kubectl` 命令行工具中,你可以使用 `--help` 参数来查看命令的帮助文档,包括 YAML 文件的格式要求和示例。例如,使用 `kubectl create --help` 命令可以查看如下内容: ``` Create a resource from a file or from stdin. JSON and YAML formats are accepted. Usage: kubectl create (-f FILENAME | --filename=FILENAME) [options] kubectl create (-k DIRECTORY | --kustomize=DIRECTORY) [options] kubectl create clusterrolebinding NAME --clusterrole=ROLE [--user=USER] kubectl create clusterrole NAME --verb=verb --resource=resource.group [--resource-name=resource.name] kubectl create configmap NAME [--from-literal=key1=value1] [--from-literal=key2=value2] [--from-file=[key=]source] [--dry-run=server|client|none] [--output=wide|yaml|json] [options] kubectl create cronjob NAME --image=image [--schedule=''] --command -- [COMMAND] [args...] [options] kubectl create deployment NAME --image=image [--dry-run=server|client|none] [--output=wide|yaml|json] [options] kubectl create job NAME --image=image --command -- [COMMAND] [args...] [options] kubectl create namespace NAME [--dry-run=server|client|none] [--output=wide|yaml|json] [options] kubectl create secret generic NAME [--from-literal=key1=value1] [--from-literal=key2=value2] [--from-file=[key=]source] [--dry-run=server|client|none] [--output=wide|yaml|json] [options] kubectl create service NAME --tcp=port1,port2,... [--dry-run=server|client|none] [--output=wide|yaml|json] [options] kubectl create serviceaccount NAME [--dry-run=server|client|none] [--output=wide|yaml|json] [options] Examples: # Create a pod using the data in pod.json. kubectl create -f ./pod.json # Create a pod based on the JSON passed into stdin. cat pod.json | kubectl create -f - # Edit the data in EDITOR (default vim). kubectl create configmap my-config --from-file=config.json --edit # Create a new namespace named my-namespace kubectl create namespace my-namespace Options: -f, --filename='': Filename, directory, or URL to files to use to create the resource -k, --kustomize='': Process a kustomization directory. This flag can't be used together with -f or -R. --edit=false: Edit the data in $EDITOR --force=false: Create resource even if it already exists --dry-run='none': Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource. -o, --output='': Output format. One of: yaml, json, wide, name, go-template-file, go-template, jsonpath-file, jsonpath. If unspecified, will default to yaml for standalone objects and table for lists. --record=false: Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists. ``` 在这个帮助文档中,你可以看到 `kubectl create` 命令支持不同类型的资源对象,包括 Pod、Deployment、Service、Secret 等。对于每个资源对象类型,文档都提供了示例和参数说明。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值