Reputation:
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.
Upvotes: 8
Views: 41794
Reputation: 17326
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
Upvotes: 1
Reputation: 135
To get current slave host :
Jenkins.getInstance().getComputer(env['NODE_NAME']).getHostName()
To get master host :
Jenkins.getInstance().getComputer('').getHostName()
Upvotes: 4
Reputation: 5682
Inspired from @kayvee for using BUILD_URL, the following worked from me:
def getJenkinsMaster() {
return env.BUILD_URL.split('/')[2].split(':')[0]
}
This returns the master's hostname or IP as it would appear in the build URL. If you also require the port number remove the second split()
.
Upvotes: 4
Reputation: 1
Try this below shell command
def host= sh(returnStdout: true, script: 'echo ${BUILD_URL/https:\\/\\/} | cut -d "/" -f1').trim()
println("Hostname : ${host}")
Upvotes: 0
Reputation: 9268
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
.
Upvotes: 5