如何将文件作为构建参数上载到jenkins管道作业

时间:2018-06-07 05:26:48

标签: jenkins jenkins-pipeline

我想上传文件作为构建参数作为jenkins管道作业的一部分,我尝试了File参数但是,它不是上传文件。控制台日志中没有任何内容,我缺少什么?

configure看起来像这样,

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

fileParam无法直接从作业访问,因为它没有上载到工作区。 此外,在主服务器或从服务器上构建的作业之间还有另一个区别(即,当作业在从服务器上构建时,必须通过通道复制文件)

以下是dsl创建工作的示例,该工作上传文件并通过电子邮件发送:

管道参数定义:

def job = pipelineJob('MAIL_WITH_UPLOADED_ATTACHMENT') {
    parameters {
        ...
        fileParam('ATTACHMENT', 'Fichier à uploader et attacher à l\'e-mail')
        ...
    }
}

声明性管道DSL:

def createFilePath(path) {
    if (env['NODE_NAME'] == null) {
        error "envvar NODE_NAME is not set, probably not inside an node {} or running an older version of Jenkins!";
    } else if (env['NODE_NAME'].equals("master")) {
        return new hudson.FilePath(null, path)
    } else {
        return new hudson.FilePath(jenkins.model.Jenkins.instance.getComputer(env['NODE_NAME']).getChannel(), path)
    }
}

def getFileParamFromWorkspace(fileParamName) {
    def paramsAction = currentBuild.rawBuild.getAction(ParametersAction.class);
    if (paramsAction != null) {
        for (param in paramsAction.getParameters()) {
            if (param instanceof FileParameterValue) {
                def fileParameterValue = (FileParameterValue)param
                if (fileParamName.equals(fileParameterValue.getName())) {
                    def fileItem = fileParameterValue.getFile()
                    if (fileItem instanceof org.apache.commons.fileupload.disk.DiskFileItem) {
                        def diskFileItem = (org.apache.commons.fileupload.disk.DiskFileItem)fileParameterValue.getFile()
                        def filePath = createFilePath(env.WORKSPACE + '/fileparam/' + fileItem.getName())
                        def destFolder = filePath.getParent()
                        destFolder.mkdirs()
                        filePath.copyFrom(diskFileItem)
                        return 'fileparam/' + fileItem.getName()
                    }
                }
            }
        }
    }
    return ''
}

pipeline {
    stages {
        stage ('Mail with uploaded attachment') {
            steps {
                script {
                    def filename = getFileParamFromWorkspace('ATTACHMENT')
                    emailext to: "${params.RECIPIENT_EMAIL}",
                        subject: "${params.SUBJECT} (via ${env.JOB_NAME} ${currentBuild.currentResult})",
                        body: """${currentBuild.currentResult}: Job ${env.JOB_NAME} build ${env.BUILD_NUMBER}
                        |
                        | More info at: ${env.BUILD_URL}""".stripMargin(),
                        attachmentsPattern: filename
                }
            }
        }
    }
}