Tuesday, September 27, 2022

[FIXED] How to update the content of an existing yaml file with Pipeline Utility Steps plugin

Issue

In my jenkins pipeline I am reading data stored in yaml file using Pipeline Utility Steps plugin

I can read data from file, now I want to update the value and write it back to the file, like this:

pipeline {
agent any

stages {

    stage('JOb B ....'){
        steps{
            script{
               def datas = readYaml file:"${WORKSPACE}/Version.yml"
               echo datas.MAJOR_VERSION //output is 111

               datas = ['MAJOR_VERSION': '222']
               writeYaml file:"${WORKSPACE}/Version.yml", data: datas
            }
        }//steps
    }//stage

}//stages

}//pipeline

But I am getting error - Version.yml already exist:

java.nio.file.FileAlreadyExistsException: /var/lib/jenkins/workspace/t-cicd-swarm-example_hdxts-job-B/Version.yml already exist.
at org.jenkinsci.plugins.pipeline.utility.steps.conf.WriteYamlStep$Execution.run(WriteYamlStep.java:175)
at org.jenkinsci.plugins.pipeline.utility.steps.conf.WriteYamlStep$Execution.run(WriteYamlStep.java:159)
at org.jenkinsci.plugins.workflow.steps.SynchronousNonBlockingStepExecution.lambda$start$0(SynchronousNonBlockingStepExecution.java:47)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Finished: FAILURE

It seems it can only write a new file and it cannot overwrite the existing file. How to update the content of an existing yaml file from my script shown above?


Solution

It looks like you need to delete or rename the original file before you overwrite it because the writeYaml method doesn't have an overwrite flag.

sh '''
  if [ -e Version.yaml ]; then
    rm -f Version.yaml
  fi
'''


Answered By - Rich Duncan
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.