Jenkins Environment Variables Build Parameters and Post Build Actions

Jenkins Environment Variables Build Parameters and Post Build Actions Explained

What Is Jenkins?

Jenkins is a free and open source automation tool used to automate the software development lifecycle. It helps teams build, test, and deploy code faster and more reliably. Jenkins is widely used for both Continuous Integration and Continuous Delivery.

In Continuous Integration, code changes are frequently merged into a shared repository and automatically built and tested to detect issues early.

In Continuous Delivery, Jenkins prepares the application for release by automating deployment steps. In most cases, a manual approval step is included before deploying to production.


Why Jenkins Is Needed in DevOps?

Jenkins is popular because it is open source, highly extensible through plugins, and backed by a strong community. It integrates easily with Git, Maven, Docker, cloud platforms, and multiple testing tools.

  • Automates repetitive tasks
  • Reduces manual errors
  • Speeds up software delivery
  • Integrates with Git, Docker, Kubernetes, AWS, and other tools
  • Supports CI and CD pipelines
  • Highly customizable using plugins

Jenkins Job Types

Freestyle Job

A Freestyle job is the most basic job type in Jenkins and is configured using the graphical user interface. It is suitable for beginners who want to automate simple build, test, or deployment tasks. It is mainly used for small projects or learning purposes.

Pipeline Job

A Pipeline job defines the entire workflow as code using a Jenkinsfile. It is commonly used for complex CI and CD pipelines and provides better control, visibility, and scalability.


Installing Jenkins on Ubuntu

Before installing Jenkins on Ubuntu, make sure the system is updated and Java is installed. Jenkins requires Java to run.

Step 1: Update the System

sudo apt update -y

Step 2: Install Java

Install OpenJDK, which is recommended for running Jenkins.

sudo apt install fontconfig openjdk-21-jre -y

Verify the Java installation:

java -version

Step 3: Add Jenkins Repository

Go to official website Jenkins.  It is recommended to use the Jenkins Long Term Support release for better stability.

Add the Jenkins repository key:

sudo wget -O /etc/apt/keyrings/jenkins-keyring.asc \
https://pkg.jenkins.io/debian-stable/jenkins.io-2023.key

Add the Jenkins repository to your system:

echo "deb [signed-by=/etc/apt/keyrings/jenkins-keyring.asc] \
https://pkg.jenkins.io/debian-stable binary/" | sudo tee \
/etc/apt/sources.list.d/jenkins.list > /dev/null

Step 4: Install Jenkins

Update the package list and install Jenkins:

sudo apt update -y
sudo apt install jenkins -y

Step 5: Enable and Start Jenkins Service

After installation, enable Jenkins to start automatically and then start the service:

sudo systemctl enable jenkins
sudo systemctl start jenkins
sudo systemctl status jenkins

Jenkins service enable

Step 6: Access Jenkins Web Interface

Open a web browser and access Jenkins using the following URL:

http://localhost:8080

Install the suggested plugins during setup.

Access Jenkins Web Interface

Step 7: Unlock Jenkins

During the initial setup, Jenkins will ask for an initial administrator password. Run the following command to retrieve it:

sudo cat /var/lib/jenkins/secrets/initialAdminPassword

Copy the password and paste it into the Jenkins setup screen.

Jenkins will ask for an initial administrator password

Step 8: Create Admin User

After unlocking Jenkins, create an admin user by providing a username, password, and email address. These credentials will be used for future logins.

Create Admin User in Jenkins


Configure the Build Step Using Bash Commands

I recommend learning basic Linux and shell scripting to better understand Jenkins, since some basic concepts are used in this blog.

Create a New Freestyle Job

  1. Click New Item
  2. Enter a job name
  3. Select Freestyle project
  4. Click OK

Creating First Job in Jenkins

Add a description to explain what the job does.
Jenkins Job Description

Add a Build Step

Scroll down to the Build section.

  1. Click Add build step
  2. Select Execute shell

This section is used to write Bash commands.

Simple Bash Command In Jenkins

Write a Simple Bash Command

In the Command field, add the following:

#!/bin/bash

echo "Hello from Jenkins!"

echo "Current date and time:"
date

echo "Running as user:"
whoami

View the console output after clicking Build Now.
Console output of bash script


Git Public Repository Integration in Jenkins

Ensure Git is installed before proceeding.

sudo apt update
sudo apt install git -y

Create a Jenkins Freestyle Job

  1. Click New Item
  2. Job name: jenkins-git-demo
  3. Select Freestyle project
  4. Click OK

Connect Jenkins to a Public GitHub Repository

In the job configuration:

  1. Go to Source Code Management
  2. Select Git
  3. Enter the repository URL
https://github.com/thedevopsguide/jenkins-demo.git

Credentials: None since the repository is public

Branch:

*/main

Go to Source Code Management section add git url

Add a Build Step

Scroll down to the Build section.

  1. Click Add build step
  2. Select Execute shell

Jenkins Bash Commands

The following Bash commands grant execution permission and run the script.

#!/bin/bash
chmod +x build.sh
./build.sh

Check the console output after clicking Build Now.
Jenkins Git integration console output


Git Private Repository Integration in Jenkins

In real world projects, most Git repositories are private for security reasons. When Jenkins pulls code from a private repository, authentication is required.

Why Credentials Are Required

  • Private repositories are protected
  • GitHub requires authentication
  • Jenkins cannot enter credentials interactively
  • Credentials must be stored securely in Jenkins

Without credentials, Jenkins may fail with errors such as:

ERROR: Repository not found
fatal: Authentication failed

ERROR Repository not found

Private Repository Structure

simple-private-repo/
├── hello.sh
└── README.md

hello.sh

#!/bin/bash
echo "Hello from Jenkins private repository!"

Create Job

Create a new item and select Freestyle Project.

Name: Jenkins-Git-Private

Source Code Management

Select Git and use HTTPS.
Create a private GitHub repository using the above files and provide the private repository URL.

Generate GitHub Personal Access Token

Go to GitHub Settings, then Developer settings, then Personal access tokens, and select Fine-grained tokens.
Git private repo settings
Git Personal access tokens classic Generate
Git Personal access tokens select scope

Token details:

  • Token name: Git_Private_Jenkins
  • Expiration: Set expiry to 7 days

Click Generate token and copy the token immediately, as it will not be shown again.

Add Token to Jenkins

Go to Jenkins, open Manage Jenkins, then Credentials.

  • Kind: Username with password
  • Username: Your GitHub username
  • Password: Paste the personal access token
  • ID: Git_Cred
  • Description: GitHub credentials for private repository

Add Git Token to Jenkins

Select the saved credentials:

Git_Cred

Provide the private repository URL, select the Git credentials from the dropdown, and choose the correct branch.

Branch:

*/main

Git Credentials Configure in Jenkins

Build Step

#!/bin/bash
chmod +x hello.sh
./hello.sh

Git Private Repo Build steps

After clicking Build Now, the output will be visible in the console output.

Expected Output

Hello from Jenkins private repository!

Environment Variables in Jenkins

Environment variables are key value pairs provided by Jenkins at runtime. They help make jobs dynamic, reusable, and easier to maintain.

Built-In Jenkins Environment Variables

VariableDescription
BUILD_NUMBERCurrent build number
JOB_NAMEName of the job
WORKSPACEPath to the job workspace
BUILD_IDUnique build identifier
BUILD_TAGBuild tag string
JENKINS_HOMEJenkins home directory
GIT_BRANCHGit branch name
GIT_COMMITGit commit ID

Create a new job, add a meaningful description, and go to the Build Steps section. Under Execute Shell, paste the following script. To view all available environment variables, use the option shown in the image below.

#!/bin/bash
echo "Job Name: $JOB_NAME"
echo "Build Number: $BUILD_NUMBER"
echo "Workspace: $WORKSPACE"
echo "Git Branch: $GIT_BRANCH"

Environment Variables in Jenkins

After saving the job and clicking Build Now, the output will be displayed in the console.
Environment Variables in Jenkins console output


Build Parameters in Jenkins

Build parameters allow users to pass values when triggering a job, making it reusable for different environments and versions.

Enable Parameters

  1. Open the job
  2. Click Configure
  3. Check This project is parameterized

After checking the box for This project is parameterized, you can see the Add Parameter option. Click on it to view the list of available parameters.
Build Parameters in Jenkins

String Parameter

  • Name: VERSION
  • Default Value: 1.0.0
  • Description: Application version

Choice Parameter

  • Name: ENVIRONMENT
  • Choices: dev, test, prod
  • Description: Select environment

Create a sample job for these build parameters. Add a description for the job, check the box for This project is parameterized, and select String Parameter. Set the name as VERSION, the default value as 1.0.0, and the description as Application version. Then select Choice Parameter and set the name as ENVIRONMENT, the choices as dev, test, and prod, and provide a description.
Choice Parameter in Jenkins

Go to Build Steps, select Execute Shell, and paste the script below.

Use Parameters in Build Step

#!/bin/bash

echo "Application Version: $VERSION"
echo "Deploying to: $ENVIRONMENT"

Parameter in Jenkins Example
After saving all configurations, you can see the Build with Parameters option on the job page. You can change the parameter values based on your requirement.
Parameter in Jenkins Build UI
After clicking Build, you can see the console output.
Parameter in Jenkins output

Boolean Parameter

A Boolean parameter provides a true or false option using a checkbox.

Create a new job, check the box for This project is parameterized, and select the Boolean Parameter.

Add Boolean Parameter

  • Name: SEND_NOTIFICATION
  • Description: Send email notification after the build
  • Default Value: Unchecked

Boolean Parameter

Go to Build Steps, select Execute Shell, and paste the script below.

#!/bin/bash

echo "SEND_NOTIFICATION value is: $SEND_NOTIFICATION"

if [ "$SEND_NOTIFICATION" = "true" ]; then
  echo "Sending email notification..."
else
  echo "Email notification skipped"
fi

In Jenkins UI:

  • Checked means true
  • Unchecked means false

Boolean Parameter Execute Shell Script

After saving all configurations, you can see the Build option with a checkbox for SEND_NOTIFICATION. Check or uncheck it based on your requirement, click the Build button, and view the console output.
Boolean Parameter Build Now UI


Post-Build Actions in Jenkins

Post-build actions run after the main build process finishes. They are commonly used to save build outputs, archive files, send notifications, or trigger other Jenkins jobs.

Archiving Artifacts in Jenkins

Artifacts are files generated during a build that you want to store, view, or download later.

Step 1: Generate a Sample Artifact

Create a new Freestyle job and go to Build Steps. Select Execute shell and add the Bash script below.

#!/bin/bash
mkdir -p output
echo "Build report for $JOB_NAME - $BUILD_NUMBER" > output/report.txt

Archiving Artifacts Bash Script

Step 2: Archive the Artifact

  1. Scroll down to Post-build Actions
  2. Click Add post-build action
  3. Select Archive the artifacts
  4. In Files to archive, enter: output/*.txt
  5. Click Save

Post-build Actions Archive the artifacts

Step 3: Verify the Artifact

  1. Run the job
  2. Click the build number
  3. You will see an Artifacts section
  4. Click report.txt to download the file

Archive the artifacts result

Triggering Another Jenkins Job

Post-build actions also allow you to chain multiple jobs together to create multi-step workflows.

Example workflow:

  • Job_1
  • Job_2

In this setup, Jenkins automatically runs Job_2 after Job_1 completes.

Step 1: Create the First Job

Create a new Freestyle job named:

Job_1

Add the following build step:

#!/bin/bash
echo "First Job running..."

Triggering Another Jenkins Job 1

Step 2: Create the Second Job

Create another Freestyle job named:

Job_2

Add the following build step:

#!/bin/bash
echo "Second Job running..."

Step 3: Trigger Job 2 from Job 1

  1. Open the configuration of Job_2
  2. Check Build after other projects are built
  3. In Projects to watch, enter: Job_1

You can control when Job_2 is triggered by selecting one of the following options:

  • Trigger only if the build is stable
  • Trigger even if the build is unstable
  • Trigger even if the build fails
  • Always trigger, even if the build is aborted

Click Save. Now, whenever Job_1 runs, Job_2 will be triggered based on the selected condition.
Triggering Another Jenkins

If your setup is correct, you can see the Downstream Projects section after the build. It will display the next build job.
Jenkins Downstream Projects Setup

After clicking Build Now in Job_1, it automatically builds Job_2.


Build Triggers in Jenkins

Build triggers in Jenkins define when a job should run automatically. Jenkins supports multiple trigger types such as:

  1. Build periodically
  2. SCM polling
  3. Webhooks

Here, SCM polling and Build periodically use cron syntax. Let us first understand what cron syntax is.

What Is Cron Syntax?

Cron syntax is used to define schedules for recurring tasks. In Jenkins, it is used for Build periodically and SCM polling. A cron expression consists of five fields that specify the time and frequency of execution.

Cron Format

FieldRangeDescription
Minute0 to 59Minute of the hour
Hour0 to 23Hour of the day
Day of Month1 to 31Day of the month
Month1 to 12Month of the year
Day of Week0 to 7Day of the week

Special characters used in cron:

  • * means every value
  • H means a hashed value for load distribution
  • is used to define a range
  • / is used to define step values

Examples:

0 11 * * * runs every day at 11 AM

5 14 1-20 2 * runs from the 1st to the 20th of February at 2:05 PM

*/5 * * * * runs every five minutes

What Is Poll SCM?

Poll SCM means Jenkins periodically checks your Git repository for changes. If Jenkins detects new commits, it automatically triggers a build.

In simple words, Jenkins keeps asking GitHub:
Has anything changed?

If changes are found, Jenkins runs the job. If not, nothing happens.

How Poll SCM Works

  1. Jenkins runs based on the configured schedule
  2. It connects to the Git repository
  3. It compares the latest commit with the previous build
  4. If changes are detected, Jenkins triggers a build
  5. If no changes are found, Jenkins does nothing

How to Implement Poll SCM

Step 1: Open Job Configuration

  1. Go to the Jenkins Dashboard
  2. Click your job
  3. Click Configure

Step 2: Enable Poll SCM

  1. Scroll to the Build Triggers section
  2. Check Poll SCM
  3. Add a cron schedule
*/5 * * * *

This means Jenkins checks the Git repository every 5 minutes.

Step 3: Save and Test

  1. Click Save
  2. Make a new commit in the Git repository
  3. Wait for up to 5 minutes
  4. Jenkins will automatically trigger the build

What Is a GitHub Webhook?

A webhook allows GitHub to directly notify Jenkins when code changes occur.

In simple words, GitHub tells Jenkins:
New code was pushed.

Jenkins immediately starts the build. This is a real time trigger and is recommended for production environments.

How Webhooks Work

  1. A developer pushes code to GitHub
  2. GitHub sends an HTTP request to Jenkins
  3. Jenkins receives the webhook event
  4. Jenkins triggers the job instantly
  5. The build starts without delay

How to Implement GitHub Webhooks

Step 1: Enable Webhook Trigger in Jenkins

  1. Open the Jenkins job
  2. Click Configure
  3. Scroll to Build Triggers
  4. Check GitHub hook trigger for GITScm polling
  5. Click Save

Step 2: Get Jenkins Webhook URL
Webhook URL format:

http://your-jenkins-url/github-webhook/

Step 3: Add Webhook in GitHub Repository

  1. Open your GitHub repository
  2. Go to Settings
  3. Click Webhooks
  4. Click Add webhook

Step 4: Configure Webhook Settings

  • Payload URL: http://your-jenkins-url/github-webhook/
  • Content type: application/json
  • Trigger events: Just the push event
  • Keep the webhook active

Click Add webhook.

Step 5: Test the Webhook

  1. Go to GitHub Webhooks
  2. Select your webhook
  3. Push new code to the GitHub repository
  4. A new build will be triggered in Jenkins

Discard Old Builds in Jenkins

By default, Jenkins stores all past builds. While this is useful for debugging and auditing, it can quickly consume disk space and impact server performance.

The Discard Old Builds feature helps automatically delete older builds based on:

  • Number of builds
  • Age of builds
  • Artifact retention

Why Discard Old Builds Is Important

  • Saves disk space
  • Improves Jenkins performance
  • Prevents server crashes due to low storage
  • Keeps only relevant build history
  • Reduces storage costs on cloud servers

How to Enable Discard Old Builds Per Job

Step 1: Open Job Configuration

  1. Go to the Jenkins Dashboard
  2. Open your job
  3. Click Configure

Step 2: Enable Discard Old Builds

  1. In the General section
  2. Check Discard old builds

Step 3: Configure Retention Rules

You will see the following options:

FieldMeaning
Days to keep buildsDeletes builds older than the specified number of days
Max number of builds to keepKeeps only the specified number of most recent builds
Days to keep artifactsDeletes artifacts older than the specified number of days
Max number of artifacts to keepKeeps only the specified number of most recent artifacts

Example Configuration

  • Days to keep builds: 14
  • Max number of builds to keep: 10
  • Days to keep artifacts: 7
  • Max number of artifacts to keep: 5

This configuration means:

  • Only the last 10 builds are kept
  • Builds older than 14 days are deleted
  • Only the last 5 artifacts are retained
  • Artifacts older than 7 days are deleted

Click Save to apply the changes.

Step 4: Verify Old Build Cleanup

  1. Run the job multiple times
  2. Wait for the retention rules to apply
  3. Older builds will be deleted automatically

Be the first to comment

Leave a Reply

Your email address will not be published.


*