Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current build's node name in jenkins using groovy

Tags:

I have a pipeline job running in Jenkins and I want to know the name of the node it's running on. Is there a way to get the node name from within the job's Groovy script?

I have tried the below code:

print currentBuild.getBuiltOn().getNodeName() 

the error is:

org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: unclassified method org.jenkinsci.plugins.workflow.job.WorkflowRun getBuiltOn 

I also tried this:

def build = currentBuild.build() print build.getExecutor().getOwner().getNode().getNodeName() 

but the result is ''.

like image 533
nanci Avatar asked Jun 26 '17 09:06

nanci


People also ask

What is node name in Jenkins?

As part of the terminology cleanup effort, the built-in node was renamed from "master node" to "built-in node" in Jenkins 2.307 and in Jenkins 2.319.

Where is my Jenkins node?

Click on Manage Jenkins in the left corner on the Jenkins dashboard. Click on Manage Nodes. Select New Node and enter the name of the node in the Node Name field.

What is Jenkins node label?

When creating a new slave node, Jenkins allows us to tag a slave node with a label. Labels represent a way of naming one or more slaves. We leverage this labeling system to tie the execution of a job directly to one or more slave nodes.

How does Jenkins choose a node?

By default, Jenkins employs the algorithm known as consistent hashing to make this decision. More specifically, it hashes the name of the node, in numbers proportional to the number of available executors, then hashes the job name to create a probe point for the consistent hash.


Video Answer


1 Answers

There is an environment variable 'NODE_NAME' which has this.

You can access it like this:

echo "NODE_NAME = ${env.NODE_NAME}" 

When you are editing a pipeline job, you can find all the available environment variables by going to the "pipeline syntax" help link (left of page) then look for the "Global Variables" section and click through to the "Global Variables Reference". There is a section "env" that lists the environment variables available.

like image 91
macg33zr Avatar answered Sep 21 '22 02:09

macg33zr