Search code examples
jenkinsyamlyq

To update a yaml file using yq command through jenkins pipeline


My sample yaml file looks like:

cluster:
  a: val1
  b: val2
  c: val3
  list:
    k1:
    - n11
    - n2
    k2:
    - n1

So, the jenkins pipeline takes 2 inputs, i.e., the name of the input1 and input2. Post creation, I need to update the yaml file. I need to add the input1 based on input2, if input2=k1, I need to input1 in k1 section. I'm trying to execute the following command in my jenkins pipeline: sh "a=$Input1 b=$Input2 yq -i '.cluster.list[strenv(b)] += strenv(a)' sample.yaml"

But it is throwing error:

jq: error: strenv/1 is not defined at <top-level>, line 1:
.cluster.vms[strenv(a)] += strenv(b)

Solution

  • Case 1: if your variable is declared in the pipeline: yq -iY .cluster.list[$key] += $val where, -iY will edit the yaml file, $key holds the value of input1 and $val holds the value of input2

    Case 2: if $key and $val are not declared, following commands work: yq -iY --arg key k1(or k2) --arg val value .cluster.list[$key] += $val