'Jenkins pipeline: How to get the hostname of the slave

I have two different Linux servers (prod and dev) with different $HOSTNAME and different certificates, which are by default named after the hostname.

Now I want to determine within the Jenkins-Pipeline on which host I am and thus use the right certificate.

To do so I wrote the following test script:

def labels = []
labels.add('jenkins_<slavehost>_x86')
def builders = [:]

for (x in labels) {
    def label = x
    builders[label] = {
        ansiColor('xterm') {
            node (label) {
                stage('cleanup') {
                    deleteDir()
                }
                stage('test') {
                    sh """
                        echo $HOSTNAME
                    """
                }
            }
        }
    }
}

parallel builders

Which does not work since the $HOSTNAME is not defined.

groovy.lang.MissingPropertyException: No such property: HOSTNAME for class: groovy.lang.Binding

How can I get the hostname of the jenkins-slave within a sh in a pipeline?


Since you can name the node in any way you like, you can't just use the NODE_NAME, it does not have to be the same as the $HOSTNAME you would get from echo $HOSTNAME on a bash on the slave machine.



Solution 1:[1]

def getJenkinsMaster() {
    return env.BUILD_URL.split('/')[2].split(':')[0]
}

You can get the hostname from the url

Solution 2:[2]

sh "echo ${env.NODE_NAME}"

You can add this shell command and get the hostname from the environment variable.

Solution 3:[3]

not sh step, but you can use groovy:

import java.security.MessageDigest
import org.jenkinsci.plugins.workflow.cps.CpsThread
import hudson.FilePath

@NonCPS
def get_current_pipeline_node() {
    def thread = CpsThread.current()
    def cv = thread.contextVariables
    def fp
    try {
        fp = cv.get(FilePath, null, null)
    } catch(MissingMethodException) {
        fp = cv.get(FilePath)
    }
    return fp?.toComputer()?.node
}
node = get_current_pipeline_node()
print(node.nodeName)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Oliver Stahl
Solution 2 Gokce Demir
Solution 3 user19145492