How to add a list item in yq version 4

Viewed 1673

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

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 e '.spec.targetNamespaces += [ "rhpam-user1" ]' yaml

See mikefarah/yq - Relative append

Related