Someone2
Someone2

Reputation: 495

Jenkins pipeline: How to get the hostname of an agent

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 correct certificate.

To do so I wrote the following test script:

def labels = []
labels.add('jenkins_<agenthost>_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-agent 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 agent machine.

Upvotes: 1

Views: 4699

Answers (3)

user19145492
user19145492

Reputation: 1

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)

Upvotes: 0

Gokce Demir
Gokce Demir

Reputation: 675

sh "echo ${env.NODE_NAME}"

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

Upvotes: 0

Oliver Stahl
Oliver Stahl

Reputation: 644

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

You can get the hostname from the url

Upvotes: 1

Related Questions