简体   繁体   中英

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

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?

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
'''

According to the latest documentation. There is a parameter you can use to overwrite the content of designated file:

writeYaml: Write a yaml from an object.
...
overwrite (optional): Allow existing files to be overwritten. Defaults to false.

Please refer to: https://www.jenkins.io/doc/pipeline/steps/pipeline-utility-steps/#writeyaml-write-a-yaml-from-an-object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM