How to get the Jenkins master IP/hostname inside a pipeline stage executing on a slave?

Viewed 31175

I have a Jenkins declarative pipeline in which I build in one stage and test in another, on different machines. I also have a Selenium hub running on the same machine as the Jenkins master.

pipeline {
  agent none
  stages {
    stage('Build') {
      agent { node { label 'builder' } }
      steps {
        sh 'build-the-app'
        stash(name: 'app', includes: 'outputs')
      }
    }
    stage('Test’) {
      agent { node { label 'tester' } }
      steps {
        unstash 'app'
        sh 'test-the-app'
      }
    }
  }
}

I'd like for the Selenium tests that run on at the Test stage to connect back to the Selenium hub on the Jenkins master machine, and that means that I need to get the IP address or hostname of the Jenkins master machine from the slave.

Is there a way to do this? The Jenkins master URL / hostname isn't in the environment variables and I'm uncertain how else to get the Jenkins master's IP address.

5 Answers

To get current slave host :

Jenkins.getInstance().getComputer(env['NODE_NAME']).getHostName()

To get master host :

Jenkins.getInstance().getComputer('').getHostName()

You can simply do it like this way:

 stage("SomeStageName") {
     agent { label 'exampleRunOnlyOnLinuxNode' }
     steps {
         script {
              println "\n\n-- Running on machine: " + "hostname".execute().text
         }
     }
 }

and "hostname -i".execute().text will print the IP

Try this below shell command

def host= sh(returnStdout: true, script: 'echo ${BUILD_URL/https:\\/\\/} | cut -d "/" -f1').trim()
println("Hostname : ${host}")
Related