Search code examples
jenkinsjenkins-pipelinejenkins-groovy

Jenkins run job with stashedfile parameter


I can run a new job from a different job with build job: 'jobname' But my new job also requires a stashed file parameter. Can this be included in the parameters[] ?


Solution

  • Passing the parameter as a io.jenkins.plugins.file_parameters.StashedFileParameterValue worked for me. StashedFileParameterValue requires a org.apache.commons.fileupload.FileItem which also needs to be created. Also FileItem is not serializable, so it needs to be created in a @NonCPS method. Combining all of that together, a simple pipeline that calls a job, stashed-file, which has a stashedFile parameter named INPUT_FILE, looks like below:

    @NonCPS
    void triggerStashedFileJob(File testFile) {
        def factory = new org.apache.commons.fileupload.disk.DiskFileItemFactory()
        def fileItem = factory.createItem('file', 'text/plain', false, 'test-copy.txt')
        fileItem.outputStream << testFile.bytes
    
        build job: 'stashed-file', parameters: [
            new io.jenkins.plugins.file_parameters.StashedFileParameterValue('INPUT_FILE', fileItem),
        ]
    }
    
    pipeline {
        agent any
    
        stages {
            stage('trigger job that needs stashed file') {
                steps {
                    deleteDir() // To cleanup workspace 
                    sh '''
                       echo "hello from parent job" >> test.txt
                    '''
    
                    script {
                        File testFile = new File("${env.WORKSPACE}/test.txt")
                        triggerStashedFileJob(testFile)
                    }
                }
            }
        }
    }