24

I am looking for a way to run a java process in background using Jenkins declarative pipeline. Below is the snippet of code

stage('Deploy'){
        steps{
            script{
                withEnv(['BUILD_ID=dontkill']) {
                    sh "nohup java -jar test-0.0.1-SNAPSHOT.war &"
                }
            }
        }
}

Already aware of ProcessTreeKiller of Jenkins and every answer suggest to do the same. I have tried using environment inside the steps block with no luck.

Jenkins version : 2.60.1

Pipeline plugin : 1.1.7

Any help is greatly appreciated.

Dharanidhar
  • 701
  • 2
  • 5
  • 10

3 Answers3

22

Any one facing the same problem and using pipeline project, set JENKINS_NODE_COOKIE instead of BUILD_ID.

Dont waste your time setting HUDSON_COOKIE, HUDSON_SERVER_COOKIE, JENKINS_COOKIE or JENKINS_SERVER_COOKIE. None of them work for pipeline project.

Refer to https://issues.jenkins-ci.org/browse/JENKINS-28182 for more details.

javabrett
  • 103
  • 3
Dharanidhar
  • 701
  • 2
  • 5
  • 10
2

Alternative solution. Use the parallel pipeline step to run your foreground and background processes as equal partners in, well, parallel.

One advantage is that you have easy access to the stdout of the background process in the Blue Ocean UI.

stage("Run") {
    parallel {
        stage('k3s') {
            steps {
                sh 'sudo /home/jenkins/k3s server --write-kubeconfig-mode 664 & echo $! > $WORKSPACE/k3s.pid; wait -n $(cat $WORKSPACE/k3s.pid) || true'
            }
        }
        stage('test') {
            steps {
                sh 'sleep 1; ps -p $(cat $WORKSPACE/k3s.pid)'
                sh 'while ! /home/jenkins/k3s kubectl get node; do sleep 1; done'
            }
            post {
                always {
                    sh 'while ps -p $(cat $WORKSPACE/k3s.pid); do sudo kill -9 $(cat $WORKSPACE/k3s.pid); sleep 5; done'
                }
            }
        }
    }
}
user7610
  • 121
  • 3
1

With a bat pipeline step it works with:

            script {
                withEnv ( ['JENKINS_NODE_COOKIE=do_not_kill'] ) {
               bat """
                   @set prompt=\$G\$S
                   cd ${RUN_DIR}
                   start \"title\" my.bat
                   start \"title\" my.cmd
                   start \"title\" my.exe
                   """
            }
        }

Gerold Broser
  • 171
  • 1
  • 10