Replace a list value in yaml with yq

168 Views Asked by At

I have a Yaml file as below and would like to replace "cups-stage-service" with "cups-stage-blue-service".

In the YAML file 'cups-stage-service' is at index 0 but not necessarily at index 0. some times it may be below 'dyn-service'. I wanted to find and replace in any index.

I would also want to use regex like "cups-stage-service.*" to find and replace it as it also not necessarily be 'cups-stage-service' but something like 'cups-stage-service-full-name'.

---
applications:
  - name: cv-service
    buildpacks:
      - dotnet_core_buildpack_latest
    stack: cflinuxfs3
    instances: 8
    memory: 1G
    disk_quota: 1G
    log-rate-limit-per-second: 24KB
    health-check-type: http
    health-check-http-endpoint: /ping
    health-check-invocation-timeout: 5
    timeout: 180
    services:
      - cups-stage-service
      - dyn-service
    env:
      ENVIRONMENT: stage
      ASPNETCORE_ENVIRONMENT: stage

I tried using yq in combination with select(), test(), and a few others but nothing works.

I wanted to do it with yq only rather than sed/awk with which it's easily achievable.

Any help is appreciated.

Thanks,

1

There are 1 best solutions below

4
pmf On BEST ANSWER

You can use test to get a boolean value from a RegEx test:

(.applications[].services[] | select(test("cups-stage-service.*"))) = "cups-stage-blue-service"
---
applications:
  - name: cv-service
    buildpacks:
      - dotnet_core_buildpack_latest
    stack: cflinuxfs3
    instances: 8
    memory: 1G
    disk_quota: 1G
    log-rate-limit-per-second: 24KB
    health-check-type: http
    health-check-http-endpoint: /ping
    health-check-invocation-timeout: 5
    timeout: 180
    services:
      - cups-stage-blue-service
      - dyn-service
    env:
      ENVIRONMENT: stage
      ASPNETCORE_ENVIRONMENT: stage

Works with kislyuk/yq, mikefarah/yq, and itchyny/gojq.