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

user8370684 picture user8370684 · Aug 9, 2017 · Viewed 23.5k times · Source

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.

Answer

ivan.sim picture ivan.sim · Aug 9, 2017

Not sure if there are better ways to do this, I am able to run

def masterIP = InetAddress.localHost.hostAddress
println "Master located at ${masterIP}"

in my Jenkinsfile. The first time I ran this code in my Jenkinsfile, the build failed with

org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: 
Scripts not permitted to use method java.net.InetAddress getHostAddress
at org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.StaticWhitelist.rejectMethod(StaticWhitelist.java:178)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor$6.reject(SandboxInterceptor.java:243)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:363)
at org.kohsuke.groovy.sandbox.impl.Checker$4.call(Checker.java:241)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:238)
at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.getProperty(SandboxInvoker.java:28)

I had to approve the method signature in Jenkins by navigating to Manage Jenkins > In-process Script Approval.