Home > Enterprise >  Jenkins pipeline: How to get the hostname of the slave
Jenkins pipeline: How to get the hostname of the slave

Time:09-17

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.

CodePudding user response:

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

You can get the hostname from the url

CodePudding user response:

sh "echo ${env.NODE_NAME}"

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

  • Related