Replace string into a multiline string

Viewed 26

I have the following yaml file:

values: |
  nameOverride: my-service
  fullnameOverride: ""
  namespace: my-ns

  containerApps:
    - name: app-frontend
      image_tag: xxxxxxx
    - name: app-backend
      image_tag: xxxxxxx

I'm looking for a way to replace e.g. xxxxxx by yyyyyy on containerApps.[app-frontend].image_tag within a multi-line value (values: |).

The output being:

values: |
  nameOverride: my-service
  fullnameOverride: ""
  namespace: my-ns

  containerApps:
    - name: app-frontend
      image_tag: yyyyyy
    - name: app-backend
      image_tag: xxxxxxx

How this can be accomplished using yq?

Any help is welcomed.

1 Answers

Here's a solution using mikefarah/yq. It decodes the multiline string using @yamld, makes the substitution using sub, and encodes the result back using @yaml.

yq '
  .values |= (
    @yamld | (
      .containerApps[] | select(.name == "app-frontend") | .image_tag
    ) |= sub("xxxxxxx", "yyyyyy")
    | @yaml
  )
'
values: |
  nameOverride: my-service
  fullnameOverride: ""
  namespace: my-ns
  containerApps:
    - name: app-frontend
      image_tag: yyyyyy
    - name: app-backend
      image_tag: xxxxxxx

To update the file in-place (instead of just outputting it), use the -i flag.

Related