yaml - yq 将额外的内容添加到 yaml

标签 yaml yq

我已经尝试了很多次不同的组合,但我无法让它工作。这是我的 yq 命令

yq -i e '(.spec.template.spec.containers[]|select(.name == "od-fe").image) = "abcd"

它应该替换成功的部署镜像,但它还将 template.spec.containers 添加到服务中。这是部署+服务yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  namespace: od
  name: od-fe
spec:
  replicas: 2
  selector:
    matchLabels:
      app: od-fe
  template:
    metadata:
      labels:
        app: od-fe
    spec:
      containers:
        - name: od-fe
          image: od-frontend:latest.  <<<replace here only
          imagePullPolicy: Always
          ports:
            - containerPort: 3000

---
apiVersion: v1
kind: Service
metadata:
  namespace: od
  name: od-fe-service
  labels:
    run: od-fe-service
spec:
  ports:
    - port: 3000
      targetPort: 3000
      protocol: TCP
  type: NodePort
  selector:
    app: od-fe

现在的问题是服务也变得

apiVersion: v1
kind: Service
metadata:
  namespace: od
  name: od-fe-service
  labels:
    run: od-fe-service
spec:
  ports:
    - port: 3000
      targetPort: 3000
      protocol: TCP
  type: NodePort
  selector:
    app: od-fe
  template:
    spec:
      containers: []

最佳答案

解决此问题的一种方法是在顶层包含一个 select 语句,以仅作用于部署类型

yq e '(select(.kind == "Deployment").spec.template.spec.containers[]|select(.name == "od-fe").image) |= "abcd"' yaml

注意:如果您使用 yq 版本 4.18.1 或更高版本,the eval flag e is no longer needed因为它已成为默认操作。

关于yaml - yq 将额外的内容添加到 yaml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71187168/

相关文章:

ruby-on-rails - 在 Rails 中从数据库重新生成 YAML 装置

inheritance - YAML 中的继承更复杂?

yaml - yq 添加带有名称和子字段的数组元素

aws-cloudformation - 使用 yq v4 将格式添加到 YAML 值

bash - 带有 bash 的 Yaml : escaping quotes in string

yaml - AWS SAM lambda 目标

Python YAML 转储指针引用

yaml - yq 命令没有将内容持久写入文件

regex - 如何自动从Yaml文件中删除kubernetes secret ?

yaml - 是否可以使用 YQ 对列表进行切片并将其写回 YAML 文件