Search code examples
jenkinsgroovyyamljenkins-groovy

Jenkins writeYaml not replacing value in yaml file


I have a yaml file with the following structure:

transfers:
- name: xyz
  cloud: aws
  subheading:
    impact: Low
    reason: ---

  artifacts:
  - name: name1
    type: type1
    source:
      hash: a1b2C3dd4    ---> VALUE TO OVERWRITE

I would like to overwrite the existing hash value with a value of the latest GIT_COMMIT.

I have tried the method from the following question: write yaml file in jenkins with groovy. However, the value of hash[0][0] remains unchanged. This is the case even when I replace env.GIT_COMMIT with a test hash string "testHash123". I'm unsure why this is the case?

def filename = ('path/to/file.yaml')
def datas = readYaml file: filename
//change hash
datas.transfers['artifacts'].source.hash[0][0] = env.GIT_COMMIT
writeYaml file: filename, data: datas, overwrite: true

Solution

  • Please try the following.

    datas.transfers[0]['artifacts'][0]['source'].hash = env.GIT_COMMIT
    

    The easiest way to figure this out is by printing, so you can understand the structure.

    [transfers:[[name:xyz, cloud:aws, subheading:[impact:Low, reason:xxxx], artifacts:[[name:name1, type:type1, source:[hash:a1b2C3dd4]]]]]]
    

    As you can see above the transfer is a sequence, so you need to extract the correct segment with an index.