Agent:决定 Pipeline 在哪台节点上跑
August 22, 2024About 2 min
Agent:决定 Pipeline 在哪台节点上跑
agent 指定整条 Pipeline(或某个 stage)在 Jenkins 的哪个节点上执行。它必须在 pipeline 块的顶层定义一次;stage 内部的 agent 是可选的,用来覆盖顶层设置。Jenkins master 就是根据这一段把任务派发到对应 agent。
any:任意可用节点
pipeline {
agent any // 顶层必须有,不能省略
stages {
stage('Build') {
agent any
steps {
echo 'Build'
}
}
}
}
用 label 指定节点
pipeline {
// agent { label 'jdk8' } 是下面写法的简写;
// node 除了 label,还能指定 customWorkspace
agent {
node {
label 'jdk8'
customWorkspace 'D:\\Jenkins' // 指定工作目录
}
}
stages {
stage('Build') {
agent {
label 'windows && jdk8' // 同时具有 windows 和 jdk8 标签
}
steps { echo 'Build' }
}
stage('deploy') {
agent {
label 'windows || jdk8' // 具有 windows 或 jdk8 标签
}
steps { echo 'Build' }
}
}
}
label 支持 && / || 组合多个标签,这在按操作系统、SDK 版本区分节点池时很常用。
用参数动态选 label
把 label 做成构建参数,一条 Pipeline 复用到不同节点池:
pipeline {
agent {
// 先判断是不是 "any":是就用空字符串(等价于 agent any),
// 否则 Jenkins 会去找名为该值的 label
label params.AGENT == "any" ? "" : params.AGENT
}
parameters {
choice(name: "AGENT", choices: ["any", "docker", "windows", "linux"])
}
stages {
stage("Build") {
steps { echo "Hello, World!" }
}
}
}
none:每个 stage 各自指定
顶层写 agent none 时不分配全局节点,每个 stage 必须自带 agent:
pipeline {
agent none // 不分配任何 agent
stages {
stage('Build') {
agent { label 'console' }
steps { echo 'Build' }
}
}
}
docker agent:用容器统一构建环境
Pipeline 插件 2.5 以后内置了 Docker 支持,直接在 agent 里指定镜像即可。注意要把 Jenkins agent 进程的用户加入 docker 用户组,否则执行 docker 命令要 sudo;加完不生效就重启 agent。
pipeline {
agent {
docker {
label 'docker'
image 'maven:3-alpine'
}
}
stages {
stage('build') {
steps { sh 'mvn clean compile' }
}
}
}
docker 块的常用选项:
label(可选):和 node 的 label 作用一样,先筛出装了 docker 的节点。image:构建时使用的镜像。args(可选):docker run时附带的参数,如args '-v /tmp:/tmp'。alwaysPull(可选):布尔,为 true 时每次都重新docker pull。
beforeAgent:先判断 when 再占用节点
默认情况下,stage 的 when 条件是进入 agent 之后才求值的。在 when 里加 beforeAgent true,可以先判断条件,只有为真才去申请节点——避免无谓地分配工作空间、排队等空闲 agent。
pipeline {
agent none
stages {
stage('Example Build') {
steps { echo 'Hello World' }
}
stage('Example Deploy') {
agent { label "some-label" }
when {
beforeAgent true
branch 'production' // 只有 production 分支才进入这个 stage
}
steps { echo 'Deploying' }
}
}
}
只有分支是 production 时才会去 some-label 节点拉代码,其它分支连节点都不占,对节点紧张的构建队列能省不少等待时间。