Search code examples
yamlyq

Change a key values based on a different value


I have the following YAML file :

affinityCookieTtlSec: 0
backends:
- balancingMode: UTILIZATION
  capacityScaler: 0.0
  group: https://www.googleapis.com/compute/v1/projects/production/regions/us/instanceGroups/prod-instance-service-green
  maxRatePerInstance: 900.0
  maxUtilization: 0.8
- balancingMode: UTILIZATION
  capacityScaler: 1.0
  group: https://www.googleapis.com/compute/v1/projects/production/regions/us/instanceGroups/prod-instance-service-blue
  maxRatePerInstance: 900.0
  maxUtilization: 0.8

Using yq, I would like to change the capacityScaler value based on group value, for example: If group is equal to https://www.googleapis.com/compute/v1/projects/production/regions/us/instanceGroups/prod-instance-service-green, change the capacityScaler in the same list to 0.5. So the output should be:

affinityCookieTtlSec: 0
backends:
- balancingMode: UTILIZATION
  capacityScaler: 0.5
  group: https://www.googleapis.com/compute/v1/projects/production/regions/us/instanceGroups/prod-instance-service-green
  maxRatePerInstance: 900.0
  maxUtilization: 0.8
- balancingMode: UTILIZATION
  capacityScaler: 1.0
  group: https://www.googleapis.com/compute/v1/projects/production/regions/us/instanceGroups/prod-instance-service-blue
  maxRatePerInstance: 900.0
  maxUtilization: 0.8

So far, I figured I can list the lists by yq e '.backends[0] or yq e '.backends[1], but I'm not able to select the correct list by the group value.


Solution

  • With the syntax you've shown in the question, I would assume you are using mikefarah/yq.

    Its DSL is almost similar to that of jq, so you can use select operator for choosing the right record and use the |= to update the desired value

    yq e '(.backends[] | select(.group == "https://www.googleapis.com/compute/v1/projects/production/regions/us/instanceGroups/prod-instance-service-green").capacityScaler) |= 0.5' yaml