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

如何使用Nushell筛选并更新数组中指定属性匹配项的取值?

使用Nushell修改YAML数组中指定元素的值

问题场景

现有如下Kubernetes Deployment的YAML配置文件:

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
      - name: myapp
        image: some-app:latest
        ports:
        - containerPort: 80

需求是仅通过Nushell将其中名为myapp的容器的image字段值更新为some-app:1.0.0。这本质是Nushell中如何筛选并修改数组指定元素的通用问题,K8s配置仅作为示例参考。

之前尝试的命令会将整个文件替换为仅包含修改后的myapp容器内容,无法保留原文件的完整结构:

open ./deployment.yaml | get spec.template.spec.containers | where name == "myapp" | update image "some-app:1.0.0" | collect | save ./deployment.yaml -f

解决方法

问题根源是之前的命令直接提取出containers数组单独修改,没有将修改后的数组放回原YAML结构中。正确的做法是在完整结构内遍历数组并修改指定元素,保留其他内容不变。

命令示例

open ./deployment.yaml | update spec.template.spec.containers {
  $in | map {
    if $it.name == "myapp" {
      $it | update image "some-app:1.0.0"
    } else {
      $it
    }
  }
} | save ./deployment.yaml -f

逻辑说明

  1. 打开目标YAML文件后,直接对spec.template.spec.containers路径执行update操作
  2. 使用map遍历数组中的每个容器对象:
    • 若容器名称匹配myapp,则更新其image字段值
    • 其他容器对象保持原样返回
  3. 最后将修改后的完整YAML结构覆盖保存回原文件

简化写法

也可以用更紧凑的语法实现相同效果:

open ./deployment.yaml | update spec.template.spec.containers (
  $in.spec.template.spec.containers | map {
    $it | if $it.name == "myapp" { update image "some-app:1.0.0" } else { $it }
  }
) | save ./deployment.yaml -f

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 10:48:15