Groovy传递shell命令来运行

时间:2016-11-07 12:48:11

标签: jenkins groovy jenkins-pipeline

使用Jenkins中的withCredentials触发传递的shell命令的函数。例如,而不是这样做

Random rnd = new Random();
int random1 = rnd.Next(1, 100);
Console.WriteLine(random1);

触发它

 withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'amazon',
                        usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']]) {
            //Shell commands block
            sh """
            echo 'hello world'
            echo 'Good bye'
            """
        }

在Jenkins的工作步骤中调用它的方法是什么?

谢谢和欢呼

2 个答案:

答案 0 :(得分:0)

只需将该块传递给withCredentials;

即可
def performWithCredentials(command_block){
    withCredentials([[$class: 'UsernamePasswordMultiBinding',
                       credentialsId: 'amazon',
                       usernameVariable: 'USERNAME',
                       passwordVariable: 'PASSWORD']], command_block)
}

答案 1 :(得分:0)

您也可以在groovy/pipelines

中编写自己的代表

你可以把它变成

performWithCredentials(delegate) {
    withCredentials([[$class: 'UsernamePasswordMultiBinding',
        credentialsId: 'amazon',
        usernameVariable: 'USERNAME',
        passwordVariable: 'PASSWORD']]) {
        delegate()
    }
}

并称之为

performWithCredentials {
    ...
    <your code here>
    ...
}

您甚至可以使用函数performWithCredentials.groovy制作文件call(..)(请参阅tutorial)并将其存储在$JENKINS_HOME/workflow-libs/中。 重新启动Jenkins并使其全局可用