CIsForCookies
CIsForCookies

Reputation: 12817

How to enforce different stages in pipeline to run on the same Jenkins agent?

My jenkinsfile looks like this:

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"
      }
    }
  }
}

Each Python script handles all the logic I need, however I must have the same agent to run the stages, and if I allow more than one option in the host param, I can't assert the agent stage I got, will be the same agent stage II will get (and without downtime, i.e. I can't allow another job use that agent between my stages).

Can I specify an agent to the whole pipeline?

Upvotes: 0

Views: 1750

Answers (1)

towel
towel

Reputation: 2214

Yes you can. In fact, you can free your master from running pipelines at all:

  • Replace agent {label "master"} with agent {label params.host}
  • Clear all the agent ( label "${params.host}" ) lines inside individual stages (you also don't need the script block, as you can run sh steps directly within the steps block)

If later on you decide you don't want to assign a single node to all stages you'll have to use scripted pipeline inside the declarative pipeline to group stages that should run on the same node:

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
  }
}

Upvotes: 1

Related Questions