jenkinsgroovyjenkins-pipelinejenkins-groovyartifacts

How to add a file I create in groovy in Jenkinsfile to the artifacts?


I have a groovy function that creates a json file and I'd like to include that file in the artifacts of the build.

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

def myFunction(path) {
    // do something
    def content = '{"foo":"bar"}'
    def file = new File("${path}foo.json")
    file.createNewFile()
    file.write(content)
}

pipeline {
    agent {
        node {
            customWorkspace pipelineCustomWorkspace
        }
    }
    stages {
        stage {
            script {
                myFunction("")
                sh("pwd")
                sh("ls")
            }
            archiveArtifacts "foo.json"
        }
    }
}

I've tried all kinds of combinations of what path to pass to myFunction and what path to add to the artifact, but no luck. Either I can't write the file to the pipelineCustomWorkspace or I seemingly manage to write the file but can't find it anywhere on the disk.


Solution

  • It's not a perfect solution, and it needs some escaping to work with json, but I was able to work around the groovy sandbox of jenkins by using sh:

    String pipelineCustomWorkspace = "/jenkins/pipeline-${BRANCH_NAME}/${BUILD_NUMBER}"
    
    def myFunction() {
        // do something
        def content = '{"foo":"bar"}'
        sh("echo ${content} > foo.json")
    }
    
    pipeline {
        agent {
            node {
                customWorkspace pipelineCustomWorkspace
            }
        }
        stages {
            stage {
                dir("bar") {
                    script {
                        myFunction("")
                        sh("pwd")
                        sh("ls")
                    }
                }
                archiveArtifacts "**/foo.json"
            }
        }
    }