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

时间:2017-02-06 12:41:42

标签: jenkins jenkins-plugins jenkins-pipeline

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

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

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

即:

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)'
    }
}

1 个答案:

答案 0 :(得分:3)

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

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();
}

不幸的是,如果你使用沙箱,你需要列出很多方法,这可能会产生一些安全后果。最好的办法是将这个util方法放在全局公共库中