最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to use yq on multiple documents, selected by content not by index - Stack Overflow

programmeradmin0浏览0评论

If I have multiple documents in one file (example.yaml), like in a k8s manifest:

kind: Service
---
kind: Deployment

Is there a way I can select documents other than by their numeric index?

My final command is like this to add alpine to the deployment:

yq '. | ( select(documentIndex==1) | .spec += {"image":"alpine"}), select(documentIndex!=0)' example.yaml
kind: Service
---
kind: Deployment
spec:
  image: alpine

But if someone flipped the sequence of documents or there was an extra document it would break.

Is there a "better" way to achieve this. (Obviously this is a super simple example and a real manifest can contain hundreds of documents and even some for the same kind. so I'd need something like kind=="Deployment" & name="nginx")

If I have multiple documents in one file (example.yaml), like in a k8s manifest:

kind: Service
---
kind: Deployment

Is there a way I can select documents other than by their numeric index?

My final command is like this to add alpine to the deployment:

yq '. | ( select(documentIndex==1) | .spec += {"image":"alpine"}), select(documentIndex!=0)' example.yaml
kind: Service
---
kind: Deployment
spec:
  image: alpine

But if someone flipped the sequence of documents or there was an extra document it would break.

Is there a "better" way to achieve this. (Obviously this is a super simple example and a real manifest can contain hundreds of documents and even some for the same kind. so I'd need something like kind=="Deployment" & name="nginx")

Share Improve this question asked Jan 31 at 15:38 MaxMax 32 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

You can select by any filter you want, e.g. by matching some parts against some literals, and then just modify the selected items while still keeping the top-level context to output all documents:

yq 'select(.kind == "Deployment").spec.image = "alpine"' example.yaml
kind: Service
---
kind: Deployment
spec:
  image: alpine

For extended selectors, just use boolean operators like and. e.g. .kind == "Deployment" and .name == "nginx"

发布评论

评论列表(0)

  1. 暂无评论