You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Jenkinsfile中Groovy生成的文件添加为构建产物?

解决Jenkins Pipeline中JSON文件无法归档为构建产物的问题

问题根源

你当前代码里用Groovy原生的new File()类操作文件,在Jenkins Pipeline环境下有隐患:Groovy代码默认可能在Jenkins master节点执行,而你的agent指定了自定义工作空间(大概率在agent节点上),导致文件实际写入的路径和你期望的agent工作空间不匹配,最终要么写入失败,要么归档时找不到文件。

修复方案

推荐用Jenkins Pipeline内置的writeFile步骤生成文件,这个步骤会自动在当前agent的工作空间内操作,彻底避免跨节点路径问题。修改后的代码如下:

String pipelineCustomWorkspace = "/jenkins/pipeline-${BRANCH_NAME}/${BUILD_NUMBER}"

def myFunction(path) {
    def content = '{"foo":"bar"}'
    // 用Jenkins内置的writeFile步骤,确保文件写入agent工作空间
    writeFile file: "${path}foo.json", text: content
}

pipeline {
    agent {
        node {
            customWorkspace pipelineCustomWorkspace
        }
    }
    stages {
        stage('生成并归档JSON') {
            steps {
                script {
                    myFunction("")
                    sh("pwd")
                    sh("ls")
                }
                archiveArtifacts artifacts: "foo.json", followSymlinks: false
            }
        }
    }
}

额外注意事项

  • 如果非要用Groovy的File类,必须确保代码在agent节点上下文执行,且明确使用工作空间的绝对路径:
    def file = new File("${pipelineCustomWorkspace}/${path}foo.json")
    
    但这种方式灵活性差,一旦agent节点变动,路径可能失效,不如writeFile通用。
  • archiveArtifacts步骤建议明确指定参数(比如artifacts和followSymlinks),避免隐式行为引发问题。

内容的提问来源于stack exchange,提问作者Gavriel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 16:19:52