首页 > 解决方案 > 如何强制管道中的不同阶段在同一个 Jenkins 代理上运行?

问题描述

我的詹金斯文件看起来像这样:

pipeline {
  agent {label "master"}
  parameters {
    string(name: "host", defaultValue: "ci_agent_001 || ci_agent_002")
  }
  stages {
    stage ("build") {
    agent ( label "${params.host}" )
    steps {
      script {
        sh "./script.py --build"
      }
    }
  }
    stage ("deploy") {
    agent ( label "${params.host}" )
    steps {
      script {
        sh "./script.py --deploy"
      }
    }
  }
    stage ("test") {
    agent ( label "${params.host}" )
    steps {
      script {
        sh "./script.py --test"
      }
    }
  }
}

每个 Python 脚本都处理我需要的所有逻辑,但是我必须有相同的代理来运行阶段,如果我在参数中允许多个选项host,我不能断言我得到的代理阶段,将是同一个代理第二阶段将获得(并且没有停机时间,即我不能允许其他工作在我的阶段之间使用该代理)。

我可以为整个管道指定代理吗?

标签: jenkins

解决方案


是的你可以。事实上,您可以完全从运行管道中解放您的主人:

  • 替换agent {label "master"}agent {label params.host}
  • 清除agent ( label "${params.host}" )各个阶段内的所有行(您也不需要script块,因为您可以sh直接在steps块内运行步骤)

如果稍后您决定不想将单个节点分配给所有阶段,则必须在声明性管道中使用脚本化管道来对应该在同一节点上运行的阶段进行分组:

stage("stages that share the same node") {
  agent { label params.host }
  steps {
    script {
      stage("$NODE_NAME - build") {
        sh "./script.py --build"
      }
      stage("$NODE_NAME - deploy") {
        sh "./script.py --deploy"
      }
      stage("$NODE_NAME - test") {
        sh "./script.py --test"
      }
    }
  }
}
stage("look at me I might be on another node") {
  agent { label params.host }
  steps {
    echo NODE_NAME
  }
}

推荐阅读