关于jenkins:如何将文本附加到jenkinsfile中的文件

How to append a text to a file in jenkinsfile

如何在Jenkinsfile中向Jenkins BUILD_ID

注入文件中的文本

我希望看到

1
version :="1.0.25"

其中25是BUILD_ID

这是我的尝试

1
2
3
4
5
6
7
8
9
import hudson.EnvVars

node {

  stage('versioning'){
    echo 'retrieve build version'
    sh 'echo version := 1.0.${env.BUILD_ID} >> build.sbt'
  }
}

错误:

version:=1.0.${env.BUILD_ID}: bad substitution

请注意文件位于当前目录中


内置writeFile的管道在这里也非常有用,但是需要一个读写过程才能追加到文件中。

1
2
3
4
def readContent = readFile 'build.sbt'
writeFile file: 'build.sbt', text: readContent+"\
\
version := 1.0.${env.BUILD_ID}"

env.BUILD_ID是一个groovy变量,而不是一个shell变量。由于您使用了单引号('),因此groovy不会替换字符串中的变量,并且外壳程序不了解${env.BUILD_ID}。您需要使用双引号"并让groovy进行替换

1
sh"echo version := 1.0.${env.BUILD_ID} >> build.sbt"

或使用外壳程序知道的变量

1
sh 'echo version := 1.0.$BUILD_ID >> build.sbt'

,由于您需要用双引号引起来的版本,因此您需要这样的内容:

1
sh"echo version := \\\"1.0.${env.BUILD_ID}\\\">> build.sbt"


我已经使用了肮脏的小包装函数来实现上述Stefan Crain的答案:

1
2
3
4
5
6
7
8
def appendFile(String fileName, String line) {
    def current =""
    if (fileExists(fileName)) {
        current = readFile fileName
    }
    writeFile file: fileName, text: current +"\
" + line
}

我真的不喜欢它,但是它可以解决问题,并且通过斜线字符串将转义的引号引起来,例如:

1
2
3
4
5
6
7
def tempFile = '/tmp/temp.txt'
writeFile file: tempFile, text:"worthless line 1\
"
// now append the string 'version="1.2.3"  # added by appendFile\
' to tempFile
appendFile(tempFile,/version="1.2.3" # added by appendFile/ +"\
")