我可以在声明式 Jenkins 管道中定义多个代理标签吗?

Can I define multiple agent labels in a declarative Jenkins Pipeline?

我正在使用 declarative Jenkins pipelines 到 运行 我的一些构建管道,想知道是否可以定义多个代理标签。

我有许多连接到我的 Jenkins 的构建代理,并且希望这个特定的管道能够由具有不同标签的各种代理构建(但不是所有代理)。

更具体地说,假设我有 2 个标签为 'small' 的代理,4 个标签为 'medium' 和 6 个标签为 'large'。现在我有一个资源非常低的管道,我希望它只在 'small' 或 'medium' 大小的代理上执行,而不是在大型代理上执行,因为它可能会导致更大的构建在队列中等待不必要的长时间。

到目前为止我看到的所有示例都只使用一个标签。 我试过这样的事情:

 agent { label 'small, medium' }

但是失败了

我使用的是 Jenkins 管道插件 2.5 版。

EDIT: I misunderstood the question. This answer is only if you know which specific agent you want to run for each stage.

如果您需要多个代理,您可以声明agent none,然后在每个阶段声明代理。

https://jenkins.io/doc/book/pipeline/jenkinsfile/#using-multiple-agents

来自文档:

pipeline {
    agent none
    stages {
        stage('Build') {
            agent any
            steps {
                checkout scm
                sh 'make'
                stash includes: '**/target/*.jar', name: 'app' 
            }
        }
        stage('Test on Linux') {
            agent { 
                label 'linux'
            }
            steps {
                unstash 'app' 
                sh 'make check'
            }
            post {
                always {
                    junit '**/target/*.xml'
                }
            }
        }
        stage('Test on Windows') {
            agent {
                label 'windows'
            }
            steps {
                unstash 'app'
                bat 'make check' 
            }
            post {
                always {
                    junit '**/target/*.xml'
                }
            }
        }
    }
}

您可以在 Jenkins 安装中查看 'Pipeline-syntax' 帮助,并查看示例步骤 "node" 参考。

您可以使用 exprA||exprB:

node('small||medium') {
    // some block
}

创建另一个标签调用 'small-or-medium',其中包含 6 个所有代理。然后在 Jenkinsfile 中:

agent { label 'small-or-medium' }

这个语法似乎对我有用:

agent { label 'linux && java' }

Jenkins pipeline documentation 和 Vadim Kotov 所述,可以在标签定义中使用运算符。

所以在你的情况下,如果你想 运行 你的作业在具有特定标签的节点上,声明的方式是这样的:

agent { label('small || medium') }

jenkins 页面中的更多示例:

// AND
agent { label('windows && jdk9 )')  }
 
// more complex one
agent { label('postgres && !vm && (linux || freebsd)')  }