Search code examples
yamlyq

How to Add/Delete/Array in YAML File using yq


I have this code in yaml

cpu-affinity:
    - management-cpu-set:
        cpu: [ 0 ]  # include only these CPUs in affinity settings

Now I am using yq version4 I want to modify this cpu array from [0] to a given list by user input and reset it back to [0] if needed.

In one way I can do like iterating and adding like cpu[0]=x , cpu[1]=y , etc But then to delete it I have to run del command for every element to reset it to cpu :[0]

Is there any way to directly replace entire array in one command with user input and reset it back to [0]


Solution

  • Using mikefarah/yq, you could use the env operator to load a YAML list and update it dynamically as

    To update the entire array with user-input do below

    user='[1, 2, 3]' reset='[0]' yq '.cpu-affinity[].management-cpu-set.cpu = env(user)' yaml
    

    and to reset it back

    user='[1, 2, 3]' reset='[0]' yq '.cpu-affinity[].management-cpu-set.cpu = env(reset)' yaml
    

    Tested on the latest release version 4.23.1