You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用yq/jq匹配镜像列表并返回完整Kubernetes Deployment对象

筛选首容器镜像匹配指定列表的Kubernetes Deployment

使用 yq(mikefarah/yq v4+)

直接通过eval-all模式加载两个文件,先提取目标镜像列表,再筛选符合条件的Deployment:

yq ea '
  ($images | .searchItems) as $searchList |
  $deployments.items[] |
  select(.spec.template.spec.containers[0].image | IN($searchList[]))
' deployments.yaml images.yaml

逻辑说明

  1. ($images | .searchItems) as $searchList:将images.yaml中的镜像列表存入变量$searchList
  2. $deployments.items[]:遍历deployments.yaml中的所有Deployment对象
  3. select(...):筛选出第一个容器镜像存在于$searchList中的Deployment,输出完整的Deployment规格

使用 jq

jq本身不直接支持YAML,需要先将YAML转为JSON,再进行筛选:

通用方式(结合yq转JSON)

yq -o json deployments.yaml | jq --argfile images <(yq -o json images.yaml) '
  .items[] |
  select(.spec.template.spec.containers[0].image | IN($images.searchItems[]))
'

支持YAML的jq版本(如gojq)

如果使用支持YAML输入输出的gojq,可以直接处理:

gojq --yaml-input --yaml-output '
  ($images | .searchItems) as $searchList |
  .items[] |
  select(.spec.template.spec.containers[0].image | IN($searchList[]))
' deployments.yaml images.yaml

示例输出

执行上述命令后,会输出匹配的完整Deployment:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.14.2
        ports:
        - containerPort: 80

内容的提问来源于stack exchange,提问作者Andrew DiNunzio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 23:05:17