Search code examples
yamlyq

How to set a field in yaml which path contains forward slash


How can I replace a field in a YAML file using the command line tool yq (version v4.30.6) which path contains a forward slash /?

My YAML file test.yaml looks like

apiVersion: v1
metadata:
  annotations:
    a.b.c/d: aaa
  namespace: bbb

I am able to replace the content of the field "metadata.namespace" but am failing to apply the same logic to "metadata.annotations.a.b.c/d" as shown below.

> MY_VARIABLE=xxx
> cat test.yaml | yq '(.metadata.namespace)|='\""$MY_VARIABLE"\" | yq '(.metadata.annotations.a.b.c/d)|='\""$MY_VARIABLE"\"
apiVersion: v1
metadata:
  annotations:
    a.b.c/d: aaa
    a:
      b:
        c/d: xxx
  namespace: xxx

I would like to replace aaa with xxx. How can I do this with yq?


Solution

  • Quote identifiers if they contain special characters (docs). Also, use env to access values from outside (environment) variables (docs).

    MY_VARIABLE=xxx yq '.metadata.annotations."a.b.c/d" = env(MY_VARIABLE)' test.yaml
    
    apiVersion: v1
    metadata:
      annotations:
        a.b.c/d: xxx
      namespace: bbb