yq 向 yaml 添加额外的内容

yq add extra contents to yaml

我尝试了很多次不同的组合,但我无法让它工作。这是我的 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 语句,仅作用于 Deployment 类型

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 因为它已成为默认操作。