如何使用Pipeline Utility Steps插件更新现有Yaml文件的内容

时间:2019-06-13 12:30:43

标签: jenkins build continuous-integration jenkins-pipeline continuous-deployment

在我的詹金斯管道中,我正在使用Pipeline Utility Steps插件读取存储在yaml文件中的数据

我可以从文件中读取数据,现在我想更新该值并将其写回到文件中,如下所示:

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

但是我遇到了错误-Version.yml已经存在:

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

似乎只能写一个新文件,不能覆盖现有文件。如何从上面显示的脚本更新现有yaml文件的内容?

2 个答案:

答案 0 :(得分:1)

由于writeYaml方法没有覆盖标志,因此您似乎需要删除或重命名原始文件,然后再覆盖它。

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

答案 1 :(得分:0)

根据最新文档。您可以使用一个参数来覆盖指定文件的内容:

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

请参考:https://www.jenkins.io/doc/pipeline/steps/pipeline-utility-steps/#writeyaml-write-a-yaml-from-an-object