在 Jenkins 管道中获取 SSH 从节点主机名/IP

cyb*_*oac 2 jenkins jenkins-plugins jenkins-pipeline

我使用 SSH 从设备作为 Jenkins 管道脚本中的节点。

有没有办法获取管道(Jenkinsfile)脚本内节点的主机名/IP?

我正在部署到参数化节点,并希望在脚本末尾回显该节点的 IP。

IE:

node('master') {
    checkout scm
    stash name: 'deploy', includes: 'modules/ci/,modules/compose/'
}

stage ('Deploy to remote server (SSH)') {
    node(${NODE}) {
        unstash 'deploy'
        withEnv(["BRANCH=${BRANCH}"]) {
            sh "chmod +x modules/ci/deployment/*"
            sh "modules/ci/deployment/update.sh"
        }
        echo 'Deployment was successful, branch ${BRANCH} was deployed to https://104.xx.xxx.xx (node IP/hostname)'
    }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*n S 6

据我所知,没有快速简便的方法可以做到这一点。以下内容检索配置的主机字段中输入的内容:

import jenkins.model.Jenkins;
import hudson.slaves.SlaveComputer;
import hudson.slaves.DumbSlave;
import hudson.plugins.sshslaves.SSHLauncher;

def getHost() {
  def computer = Jenkins.getInstance().getComputer(env.NODE_NAME);
  if (!(computer instanceof SlaveComputer)) {
    error "Not a ordinary slave";
  }
  def node = computer.getNode();
  if (!(node instanceof DumbSlave)) {
    error "Not a dumb slave";
  }
  def launcher = node.getLauncher();
  if (!(launcher instanceof SSHLauncher)) {
    error "Not a SSHLauncher";
  }
  return launcher.getHost();
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,如果您使用沙箱,您需要将大量方法列入白名单,这可能会产生一些安全后果。最好的办法是将这个 util 方法放入全球公共图书馆