如何在Jenkins Pipeline配置中定义和使用函数?

时间:2017-02-10 11:41:29

标签: jenkins groovy jenkins-pipeline

我正在尝试使用内部函数创建一个任务:

def doCopyMibArtefactsHere(projectName) {
    step ([
        $class: 'CopyArtifact',
        projectName: $projectName,
        filter: '**/**.mib',
        fingerprintArtifacts: true, 
        flatten: true
    ]);
}

def BuildAndCopyMibsHere(projectName, params) {
    build job: $project, parameters: $params
    doCopyMibArtefactsHere($projectName)
}


node { 
    stage('Prepare Mib'){
        BuildAndCopyMibsHere('project1')
    }
}

但这让我有一个例外: java.lang.NoSuchMethodError:在步骤中没有找到这样的DSL方法'BuildAndCopyMibsHere

有没有办法在Pipline脚本中使用嵌入式功能?

2 个答案:

答案 0 :(得分:27)

首先,当您在字符串之外时,不应添加$(第一个函数中的$class是异常),所以它应该是:

def doCopyMibArtefactsHere(projectName) {
    step ([
        $class: 'CopyArtifact',
        projectName: projectName,
        filter: '**/**.mib',
        fingerprintArtifacts: true, 
        flatten: true
    ]);
}

def BuildAndCopyMibsHere(projectName, params) {
    build job: project, parameters: params
    doCopyMibArtefactsHere(projectName)
}
...

现在,至于你的问题;第二个函数接受两个参数,而您只在调用时提供一个参数。您必须在通话时提供两个参数:

...
node { 
    stage('Prepare Mib'){
        BuildAndCopyMibsHere('project1', null)
    }
}

...或者你需要在函数的第二个参数中添加一个默认值:

def BuildAndCopyMibsHere(projectName, params = null) {
    build job: project, parameters: params
    doCopyMibArtefactsHere($projectName)
}

答案 1 :(得分:1)

已解决! build job: project, parameters: params时,来电java.lang.UnsupportedOperationException: must specify $class with an implementation of interface java.util.List失败并显示错误params = [:]。用params = null替换它解决了这个问题。 这是下面的工作代码。

def doCopyMibArtefactsHere(projectName) {
    step ([
        $class: 'CopyArtifact',
        projectName: projectName,
        filter: '**/**.mib',
        fingerprintArtifacts: true, 
        flatten: true
    ]);
}

def BuildAndCopyMibsHere(projectName, params = null) {
    build job: project, parameters: params
    doCopyMibArtefactsHere(projectName)
}
node { 
    stage('Prepare Mib'){
        BuildAndCopyMibsHere('project1')
    }
}