Tutorial: Jenkins Pipeline file with Apache Groovy (Step by Step)

Tutorial: Jenkins Pipeline file with Apache Groovy (Step by Step). Well, Jenkins is one of the most beloved automation and orchestration servers for Java deployments. Today, with a comprehensive graphical interface and a slew of plugins enable CI/CD and DevOps pipeline engineers to craft workflows without manual scripting.

Simply put, Jenkins generates the pipeline and configuration file for you. 

Hence, the following guide explores some of the parts of a Jenkins Pipeline file and how to edit or write your own using Groovy. 

The Relationship Between Jenkins and Groovy Script

Jenkins (FKA Hudson) was written in and for Java programming. Initially used to compile, build and deploy Java applications. On the other hand, Apache Groovy Script was created to add dynamism and compactness to Java programming. One of the many reasons Jenkins uses Groovy script for its pipeline files.

Since Jenkins is a cross platform application that runs on the Java Virtual Machine (JVM). Thus, it is important that it has a domain-specific language (DSL) that is parsed and runs similarly to languages like Python or Perl. Hence, it does not use standard Java.

What is a Jenkins Pipeline File?

A Jenkins pipeline file is an extensionless file containing Groovy Script code. The Jenkins pipeline file is usually named **Jenkinsfile**. Not only does it allow you to add complex configurations to your CI/CD pipeline but it also makes it easier to work with, edit and manage your pipeline as a software development team.

Ultimately, it allows you to view your Jenkins pipeline as code. This means that your pipeline is placed in a repository just like any other software development project. This eases collaboration and management of your pipeline.

The Pipeline plugin (Workflow Aggregator) facilitates most of Jenkin’s pipeline-as-a-code functionality. It’s a collection of various plugins , including the Pipeline API, build steps, etc. You apply these plugins from the Jenkins plugin manager

Create Jenkins Pipeline File

What is more, Jenkins allows you to set your pipeline up using either a declarative (domain-specific language) or scripted approach. Both are ultimately based on Apache Groovy script. We focus on the declarative approach as it’s easier to read and embed script into it, if needed.  

Set up a simple Jenkins Pipeline File by using Jenkins’ wizard. To initiate your first Jenkins Pipeline file with Apache Groovy script, perform the following steps:  

  • Log into Jenkins, navigate to the dashboard, and click on the + New Item option:
  • Enter the name of your Pipeline on the next screen. To keep it simple, call it Test Pipeline
  • Next, scroll down and select the Pipeline option.
  • Click OK.
  • Next, you are asked to provide a description of your pipeline. Give it a simple description such as “A demo pipeline showing you how to build a Jenkins Pipeline file”.
  • Leave everything else as it is, then click on the Pipeline option on the left Configure panel.
  • You are able to develop your Jenkins Pipeline script. Moreover, Jenkins also supplies you with a collection of convenient template/sample scripts. Select Pipeline Script from the Definition drop down menu.
  • Next, select Hello World from the Sample Script.

Before continuing with the rest of the steps, let’s analyse the script that Jenkins created for us. As you see, Jenkins creates a simple Hello World sample script. It essentially showcases some of its Apache Groovy declarative syntax.

Analyze The Sample Pipeline Script

The first line contains the `pipeline {` block declaration. Essentially, it represents your pipeline/workflow. The code/declarations contained between this block define the steps or work your pipeline must perform (sections).

The declaration is typically followed by the `agent` section. Describes which parts of your pipeline run in which parts of the Jenkins Environment. Agents are either the top level (assigned to your entire pipeline) or stage-specific. For now, we leave this option. 

The `stages` directive usually follows the `agent` (or its `option`) directive. It contains at least one stage that is divided into one or more steps. Each stage is usually labelled according to its purpose or phase in a pipeline. For instance, the above example contains a single stage named “Hello World”. Its job is to print the text “Hello World” out to the terminal, using its steps.

Unlike the stages and the other sections we covered, the steps  directive does not contain subsections or sub-blocks. However, define different steps with various uses and parameters. For instance, the `script` step allows you to embed more high-level Groovy Script into your workflow.

Nevertheless, in our Jenkins generated sample, the echo command is used to print out a string of text (“Hello World”). The rest of the pipeline file features closing braces for each declaration/directive.

Run and Edit The Pipeline File

Now that you’ve explored all the various parts of the Jenkins pipeline file, you can save your Pipeline script.   

1.Ensure the Groovy Sandbox option is ticked before clicking the Save. 

2. This takes you to Pipeline build screen where you essentially run your Pipeline. Click on the Build Now option.

3. Jenkins populates the Stage View with information related to each stage and step of your pipeline.

4. Reveal a more focused version of this view by clicking on the Full Stage View button. However, we are more interested in the build output:

  • Click on the build number (i.e. #1) under the Build History option.
    **Note: Do not click on the downfacing arrow next to the build name/number. Click on the build name/number itself. Also use the Permalinks from the main panel to access your previous builds.

5. The next screen shows info regarding your build. Select the Console option from the left panel. This reveals various stages and steps of your pipeline including the print output. View and save this information as a text file by clicking on the View as plain text option on the left panel.

Jenkins Pipeline Console Output
  • Get a more manageable and organized display of your build’s processes and actions by clicking on the Pipeline Steps option. 

Run Your Pipeline Script from Your File System

That’s how you write and manage your Pipeline script using the classic Jenkins UI. But what if you want to open it in a source code editor or IDE? Where does Jenkins store this file?

Your pipeline is currently configured to run through a pipeline script that is implanted into the Jenkins server. What if you want to create and run a custom Jenkins file located in your filesystem? Use these steps:

A.  Select the Configure option from the left panel.

B. Select Pipeline Definition from SCM from the Definition drop-down menu.

C. Next, set None as your SCM. 

D. Leave everything else and click Save.

Continue with the steps below

E. Next, open your file explorer and navigate to your Jenkins Pipeline workspace script folder. For Windows users, it is located at:
C:\ProgramData\Jenkins\.jenkins\jobs\Test Pipeline\workspace@script
Find the SCM-Key configuration text file in this folder. 

F. Single click on SCM-Key configuration text file so it is selected (not opened).

G. Press F2 Key on your keyboard to rename it (or select rename from the right-click context menu).

H. Copy all the text before the -scm-key.txt:

I. Create a new folder (Ctrl+Shitft+N) and paste the text you copied in the previous step as its name:

J. Open a text or source code editor such as Notepad. We used Notepad++.

K. Create a new file (Ctrl+N for Notepad++).

L. Paste the following text into it:

				
					pipeline {
    agent any

    stages {
        stage('Hello') {
            steps {
                echo 'Hello World From Custom Script'
            }
        }
    }
}

				
			

M. Note the above code now prints out Hello World From Custom Script

N. Save the file as (Ctrl + Alt + S for Notepad++) Jenkinsfile in the new workspace folder you created. Make sure that the file does not have an extension. It must be a generic file:

O. Now return to Jenkins Pipeline UI and build the script.

If you’ve followed all the above steps correctly, then your console output should resemble the following image:

Now edit the Jenkins script from Notepad++ and build it from Jenkins on the fly. A cleaner and easier way to manage your Jenkinsfile is through an SCM like Git/GitHub.

RunYour Pipeline Script from a SCM Repository

Firstly, create a new public GitHub repository. A readme file is not required. Your GitHub repository’s root folder should be populated with the gitattributes file and the Jenkinsfile you created earlier. We do recommend editing the Jenkinsfile slightly so that it echoes the message ‘Hello World From Github’. Nevertheless, your repo should resemble the following image:

  • Return to the Jenkins UI and configure your pipeline once again.
  • Keep the Pipeline script from SCM option configured as your Pipeline definition.
  • Select Git as your SCM.
  • Add a fully qualified link to your GitHub Repository. 
  • Select -none- as your Credentials.
  • Scroll down to Branches to build and set */* as the Branch Specifier.
  • Leave everything else and click Save.

You can now build your pipeline. This time the console output reveals a longer wall of text. If you scroll to the bottom, you are confronted with the following output:

Github Jenksinfile Console Output

Tutorial: Jenkins Pipeline file with Apache Groovy Conclusion

The above tutorial showed you how to create a Jenkins Pipeline file with Apache Groovy. To reiterate, you can extend the functionality of the DSL approach and integrate more straightforward Groovy Script by using the Script directive. This allows you to perform more complex operations such as setting environment variables for your pipeline. Manually scripting your pipelines allows you to have more control and flexibility over them.   

We recommend reading Apache Groovy’s guides and tutorials in addition to Jenkins’. As always, thank you for reading.     

Avatar for Mduduzi Sibisi
Mduduzi Sibisi

Mdu is an Oracle-certified software developer and IT specialist, primarily focused on Object-Oriented programming for Microsoft and Linux-based operating systems. He has over a decade of experience and endeavors to share what he's learned from his time in the industry. He moonlights as a tech writer and has produced content for a plethora of established websites and publications - including this one. He's always open to learning and growing.

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x