问题
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