Home > Blockchain >  Using hostname to find Nodename or label to connect to Node
Using hostname to find Nodename or label to connect to Node

Time:08-20

I have hostname that is found in a xml file but would need to use that hostname to get the node name in Jenkins to be able to connect to that node and do the scripting.

The hostname is example.co.uk and would like to use script to find the hostname in jenkins and get the node name of the Jenkins and use that as find-hostname. Is this possible?

//// 


      
    stage('use_nodename_found') {
    
    
        node("$find-hostname") {
            unstash 'db-process'
    sh """
        sudo su - postgres -c  'echo -e "-------------------------------System Information of current node running --------------------"'
    
    
    
    """.stripIndent()

CodePudding user response:

You can use the following script to retrieve the Node name passing the Host. If you want to get the labels instead of node.getNodeName() call node.getLabelString(). Read more here.

def getNodeName(def host) {
    for(def node : Jenkins.instance.getNodes()) {
      if(node.getLauncher().getHost() == host){
        return node.getNodeName() 
      }
    }
    return null
}

Note: This is a basic script, make sure you d proper error handling.

Update: Print all Hosts

def getNodeName(def host) {
    for(def node : Jenkins.instance.getNodes()) {
        println node.getNodeName() 
        println node.getLauncher().getHost()
    }
    return null
}

Following is a full scripted Pipeline.

node {
    stage('Test') {
        echo getNodeName("172.17.0.3")
    }
}

def getNodeName(def host) {
    for(def node : Jenkins.instance.getNodes()) {
      if(node.getLauncher().getHost() == host){
        return node.getNodeName() 
      }
    }
    return null
}
  • Related