0
votes

in Jenkins declarative pipeline, is there a way to set a global environment var of a stage based on the output of the previous stage? I would like to be able to dynamically set an agent based on this. I have a code that does not work (below), but this illustrates what I am trying to do:

pipeline {
  agent { node { label 'standard' } }

  stages {
    stage ('first') {
      steps {
        sh 'MYSTRING=`myapp.py getstring`'
      }
    }
    stage ('second') {
      agent { node { label "${MYSTRING}-agent" } }
      ...
    }
  }
}
1
You are setting an ephemeral shell variable to the value of a stdout. You need to set a Jenkins variable to the value of a stdout.Matt Schuchard

1 Answers

1
votes

This would work.

class Global{
    static nextNode
}

pipeline {
  agent { label 'standard' } 
  stages {
    stage ('first') {
      steps {
          script {
            Global.nextNode=sh(script: 'myapp.py getstring', returnStdout: true).trim()
          }
      }
    }
    stage ('second') {
      agent { label "${Global.nextNode}-agent" } 
    }
  }
}

But I would strongly recommend that you forget about the declarative pipeline syntax as it will probably cause you to grow gray hairs very quickly!

Below is an example in scripted mode. The below example actually works while the above one requires two executors. In my case the master node only has one and so it doesn't work as the agents are nested.

node('linux') {
  stage ('first') {
    nextNode=sh(script: 'echo \$NODE_NAME', returnStdout: true).trim()
    echo nextNode
  }
}

node ("${nextNode}") {
  stage ('second') {
    echo nextNode
    sh 'ls'
  }
}