Search code examples
yq

How to add a list item in yq version 4


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...


Solution

  • I am not sure how I missed updating my question with the solution I found, but here it is...

    Because there is only one array element I was able to get it working with this:

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

    I did not test the solution suggested by @Inian.