如何让 Jenkins master IP/hostname 进入在 slave 上执行的流水线阶段?

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

我有一个 Jenkins 声明式管道,我在其中一个阶段构建并在另一个阶段测试,在不同的机器上。我还有一个 Selenium hub 运行ning 在与 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'
      }
    }
  }
}

我希望 运行 在测试阶段进行的 Selenium 测试能够连接回 Jenkins 主机上的 Selenium 集线器,这意味着我需要获取 IP 地址或主机名来自从机的 Jenkins 主机。

有办法吗? Jenkins master URL /主机名不在环境变量中,我不确定如何获取 Jenkins master 的 IP 地址。

不确定是否有更好的方法,我可以运行

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

在我的 Jenkins 文件中。我第一次在我的 Jenkinsfile 中 运行 这段代码时,构建失败

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.reject(SandboxInterceptor.java:243)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:363)
at org.kohsuke.groovy.sandbox.impl.Checker.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)

我必须通过导航到 Manage Jenkins > In-process Script Approval 来批准 Jenkins 中的方法签名。

试试下面的 shell 命令

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

受@kayvee 使用 BUILD_URL 的启发,以下是我的工作:

def getJenkinsMaster() {
    return env.BUILD_URL.split('/')[2].split(':')[0]
}

这 returns 主机的主机名或 IP,因为它会出现在构建 URL 中。如果您还需要端口号,请删除第二个 split().

获取当前slave主机:

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

获取主控主机:

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

你可以简单地这样做:

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

"hostname -i".execute().text 将打印 IP