Get SSH slave node hostname/IP in Jenkins pipeline

[亡魂溺海] 提交于 2020-12-12 08:28:48

问题


I'm using SSH slaves as nodes in a Jenkins pipeline script.

Is there a way to fetch the hostname/IP of the node inside the pipeline (Jenkinsfile) script ?

I'm deploying to a parameterized node and would like to echo the IP of the node at the end of the script.

i.e:

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:


As far as I know there is no quick and easy way to do this. The following retrieves what ever is entered in host field of the configuration:

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

Unfortunately if you use sandbox you need to white list a whole lot of methods and it might have some security consequences. The best thing would be to put this util method in a Global Public Library



来源:https://stackoverflow.com/questions/42068095/get-ssh-slave-node-hostname-ip-in-jenkins-pipeline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!