Home > Mobile >  How to get hostname and IP address of an arbitrary jenkins node in a pipeline job
How to get hostname and IP address of an arbitrary jenkins node in a pipeline job

Time:05-11

I have a jenkins pipeline job that is parametrized. The only parameter is of type Node (named myNode), where I have always available all the nodes of the jenkins server.

enter image description here

In my groovy pipeline, I want to set two variables:

 - hostname of the node (myNode)
 - IP address of the node (myNode)

I tried many options but I can't get both hostname and IP address and I also get different results depending if the slave is windows or linux. In my mind, because jenkins know the nodes, it would be something simple but it seems is not.

What I've tried:

def find_ip(node_name){
    for (slave in Jenkins.instance.slaves) {
        host = slave.computer.hostName
        addr = InetAddress.getAllByName(host)
        if (! slave.name.trim().equals(node_name.trim())) { continue }
        String rawIpAddress = addr[0]
        ipAddress = rawIpAddress.substring(rawIpAddress.lastIndexOf("/")   1)
        print "ipAddress: "   ipAddress
        
        return host
    }
}

node('master') {
    stage('stage1') {
        println "hostname: "   find_ip(env.myNode)
    }
}

If the slave is windows, I get the hostname and ipaddress correctly. If it's linux, I get the IP address on both fields.

Thanks in advance

CodePudding user response:

def find_ip(node_name){
    def node = Jenkins.instance.slaves.find{it.name.trim()==node_name.trim()}
    if(node) {
        def addr = InetAddress.getByName(node.computer.hostName)
        def ip = addr.getHostAddress()
        def host = addr.getHostName()
        println "host=${host} ip=${ip}"
        return host
    }
}
  • Related