CHAPTER 06
Writing Jenkinsfile Pipelines
Updated: May 15, 2026
25 min read
# CHAPTER 6
Writing Jenkinsfile Pipelines
1. Introduction
In Chapter 5, we created a basic "Hello World" pipeline. But real-world CI/CD requires much more than simply echoing text to the screen. You need to define variables (like which server to deploy to), execute complex shell scripts, and tell Jenkins what to do if a step fails. In this chapter, we will dive deeper into the Declarative Pipeline syntax, mastering Environment Variables, thesh step, and the post block for handling build resolutions.
2. Learning Objectives
By the end of this chapter, you will be able to:-
Define and use Global Environment Variables in a
Jenkinsfile.
-
Execute Linux shell commands (
sh) and Windows batch commands (bat).
-
Use the
postblock to handle Success, Failure, and Always conditions.
- Understand how to structure a professional, multi-stage pipeline.
3. Beginner-Friendly Explanation
Imagine building a Lego car.-
Environment Variables: Before you start, you agree on some rules.
CARCOLOR = Red,WHEELSIZE = Large. You write this on a whiteboard. Every builder can look at the whiteboard instead of asking.
-
The
shStep: This is the actual physical action. "Snap the red brick onto the base." In Jenkins, this is where you type actual Linux terminal commands.
-
The
postBlock (Cleanup): When the car is finished, regardless of whether it looks good or if you broke a piece, you *always* sweep the floor and put the extra pieces away. In Jenkins, thepostblock ensures cleanup and notifications happen, no matter what went wrong.
4. Executing Commands (sh and bat)
The steps block is where the work happens. The most common step is sh (execute a Linux Shell script).
If Jenkins runs on a Windows server without WSL, you must use bat instead of sh.
groovy
5. Environment Variables
Pipelines often need data that changes depending on the context (e.g., "Are we deploying to Staging or Production?"). We define these in theenvironment block.
groovy
6. Mini Project: Build a Resilient Multi-Stage Pipeline
Let's build a professional pipeline that compiles code and cleans up after itself.Step-by-Step Walkthrough:
Update your Jenkinsfile with the following code. Note the new post section at the very end.
groovy
7. Real-World Scenarios
A junior developer wrote a pipeline that created heavy, 2GB temporary database files during the "Test" stage. They didn't include apost { always { ... } } cleanup block. When the tests passed, the pipeline ended, leaving the 2GB file on the server. Because they deployed 10 times a day, the Jenkins server hard drive filled up entirely by Friday afternoon, crashing the server and halting all company deployments. A simple post { always { sh 'rm -rf tempdb' } } would have prevented the outage.
8. Best Practices
-
Use Single Quotes vs Double Quotes: In Groovy/Jenkins syntax, use single quotes (
'text') for static text. You MUST use double quotes ("text") if you want to inject an environment variable (e.g.,"Deploying ${APPVERSION}"). If you use single quotes, it will print the literal dollar sign.
9. Security Recommendations
-
Do not define passwords in the Environment block: Never write
DBPASSWORD = 'password123'in theenvironmentblock of a Jenkinsfile. This file is saved in Git in plaintext for anyone to read. We will learn how to handle secure credentials in Chapter 14.
10. Troubleshooting Tips
-
The "No Such File" Error: If your
shstep fails saying a file doesn't exist, remember that Jenkins runs these commands inside a temporary "Workspace" directory. Usesh 'pwd'andsh 'ls -la'as your first debugging steps to figure out exactly where Jenkins is "standing" on the server.
11. Exercises
-
1.
What is the difference between single quotes (
') and double quotes (") when writing ashstep in a Jenkinsfile?
-
2.
Why is the
alwayscondition inside apostblock critical for server maintenance?
12. FAQs
Q: Can I run Python scripts instead of bash scripts? A: Yes! As long as Python is installed on the Jenkins server (or inside the Docker container acting as the agent), you can simply writesh 'python3 script.py'.
13. Interview Questions
-
Q: Explain the purpose and standard use cases of the
postblock in a Declarative Pipeline. Contrast thealways,success, andfailureconditions.
-
Q: A developer complains that their environment variable
$APIKEYis evaluating literally as the string "$API_KEY" instead of the actual key value. What Groovy syntax error is the developer making?
14. Summary
In Chapter 6, we evolved our pipelines from basic text echoing to functional scripts. We learned how to define Global Environment Variables to keep our code DRY (Don't Repeat Yourself), and how to execute powerful server commands using thesh step. Finally, we explored the critical post block, enabling our pipelines to handle failures gracefully, trigger notifications, and ensure the workspace is swept clean regardless of the build outcome.
15. Next Chapter Recommendation
We know how to write theJenkinsfile, but currently, we have to manually click "Build" to make it run. We need Jenkins to detect when we write code and trigger itself automatically. Proceed to Chapter 7: Git and GitHub Integration.