gpt4 book ai didi

jenkins - 无法通过 Jenkins 管道作业的 jenkinsfile 中的 Groovy 代码(或 java 代码)创建文件

转载 作者:行者123 更新时间:2023-12-01 07:51:24 32 4
gpt4 key购买 nike

pipeline {
agent any

stages {
stage('Build') {
steps {
echo 'Building..'
echo "whoami".execute().text
script {
File f = new File('/home/jenkins/test2.txt');
f.createNewFile();
}
}
}
stage('Test') {
steps {
echo 'Testing..'
}
}
stage('Deploy') {
steps {
echo 'Deploying....'
}
}
}
}

Jenkins console log: (got exception: Started by user Edgar Yu Running in Durability level: MAX_SURVIVABILITY [Pipeline] node Running on Jenkins in /var/jenkins_home/workspace/test2 [Pipeline] { [Pipeline] stage [Pipeline] { (Build) [Pipeline] echo Building.. [Pipeline] echo jenkins

[Pipeline] script [Pipeline] { [Pipeline] } [Pipeline] // script [Pipeline] } [Pipeline] // stage [Pipeline] stage [Pipeline] { (Test) Stage 'Test' skipped due to earlier failure(s) [Pipeline] } [Pipeline] // stage [Pipeline] stage [Pipeline] { (Deploy) Stage 'Deploy' skipped due to earlier failure(s) [Pipeline] } [Pipeline] // stage [Pipeline] } [Pipeline] // node [Pipeline] End of Pipeline java.io.IOException: Permission denied at java.io.UnixFileSystem.createFileExclusively(Native Method) at java.io.File.createNewFile(File.java:1012)

最佳答案

这是因为 Jenkins 没有实现 Groovy 本身,而是一个解释器 (CPS) - https://github.com/cloudbees/groovy-cps

为了帮助处理引入的复杂性,我们实现了一些通用步骤来解决创建文件等任务的麻烦。

要使用开箱即用的 Jenkins 管道步骤,请使用 writeFile:
https://jenkins.io/doc/pipeline/steps/workflow-basic-steps/#code-writefile-code-write-file-to-workspace

writeFile([file: 'file.txt', text: filetxt])

如果您对自己编写的死板,我建议将其拆分为共享库,请注意这可能会导致需要批准的 ScriptSecurity 警报:
final class PipelineUtils implements Serializable {
private script=null
private static final PipelineUtils instance = new PipelineUtils()
@NonCPS
String saveFile(String filename, String text) {
String PWD = script.pwd()
String filePath = "${PWD}/${filename}"

File file = new File(filePath)
file.text = text
}
}

https://github.com/jenkinsci/pipeline-plugin/blob/master/TUTORIAL.md有关@NonCPS 和不可序列化对象的信息。

关于jenkins - 无法通过 Jenkins 管道作业的 jenkinsfile 中的 Groovy 代码(或 java 代码)创建文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48784194/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com