Jenkins

Jenkinsfile Node Example

The node block in a Jenkinsfile allows you to specify a series of steps that should be run on a particular node. A node is a machine that is part of the Jenkins environment and is capable of executing a pipeline.

The node block can be used to specify the node on which the steps should be run, as well as any options or parameters for the node. For example, you might use a node block to specify that a specific set of steps should be run on a particular label or a specific node with certain capabilities.

In this short tutorial, we will discuss how we can use the node block to define the steps run on a given node.

Syntax

The following shows the basic syntax of the node block in a given Jenkinsfile.

node('label') {
  // steps to be run on a node with the specified label
}

In this example, the steps within the block will be run on a node with the specified label. The label can be a predefined that is configured in the Jenkins environment, or it can be a dynamically-generated that is calculated at runtime.

Example Demonstration

The following is a simple example demonstrating how we can use the node block to execute specific Jenkins steps on a given node:

pipeline {
  stages {
    stage('Check versions') {
      steps {
        node('macOS') {
          sh 'mvn --version'
          sh 'git --version'
        }
      }
    }
  }

}

The above Jenkinsfile defines a pipeline with a single stage called Check versions. Within the stage, the pipeline contains a node block that specifies that the steps within the block should be run on a node with the label macOS. The node block contains two steps that execute the mvn and git commands to print the version information.

Querying the installed Maven and Git version can help ensure maximum compatibility with the following stages of the pipeline.

The following is the same pipeline using the agent block instead of the node block:

pipeline {
  agent {
    label 'macOS'
  }
  stages {
    stage('Check versions') {
      steps {
        sh 'mvn --version'
        sh 'git --version'
      }
    }
  }

}

Conclusion

In this, you learned how you could use the node block in a Jenkinsfile to define a set of steps that should be executed on a given node.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list