Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a list item in yq version 4

Tags:

yq

I am migrating a script from yq 3 to yq 4 and cannot get one thing working.

I have the following YAML and want to add a list item after targetNamespaces:

apiVersion: operators.coreos.com/v1
kind: OperatorGroup
metadata:
  name: businessautomation-operator
  namespace: rhpam-user1
spec:
  targetNamespaces:

So the output should be:

apiVersion: operators.coreos.com/v1
kind: OperatorGroup
metadata:
  name: businessautomation-operator
  namespace: rhpam-user1
spec:
  targetNamespaces:
  - rhpam-user1

This command worked for changing the namespace:

yq eval '.metadata.namespace = "rhpam-user1"' -i ./file.yaml

When I run the following I am getting an error:

yq eval '.spec.targetNamespaces[+] = "rhpam-user1"'  -i ./file.yaml 

Error: '' expects 2 args but there is 1

I can't seem to get the new yq command structure right...

like image 243
Bryon Avatar asked Oct 24 '25 09:10

Bryon


1 Answers

If the targetNamespaces is intended to be used as an array type, you need to enclose the target string in [..], with += as below (as tested on version 4.11.2)

yq '.spec.targetNamespaces += [ "rhpam-user1" ]' ./file.yaml 

Use the -i flag for in-place substitution of the file, if the output appears as expected.

See mikefarah/yq - Relative append


Note: Since 4.18.1, yq's eval/e command is the default command and no longer needs to be specified.

like image 135
Inian Avatar answered Oct 27 '25 06:10

Inian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!