How to Write Jenkins Pipeline ?

In this article we are going to cover How to write Jenkins pipeline, why pipeline in Jenkins, Concept of pipeline in Jenkins, Approach to writing a Jenkins Pipeline and Declarative Pipeline vs Scripted Pipeline.

What is Jenkins Pipeline?

Jenkins Pipeline, often referred to as simply “Pipeline” (with a capital “P”), is a powerful and extensible plugin suite for Jenkins that enables the creation, automation, and management of continuous integration and continuous delivery (CI/CD) pipelines. These pipelines serve as automated workflows that guide software from version control repositories through various stages of building, testing, and deployment, ultimately delivering it to end-users and customers.

Why Pipeline in Jenkins?

The use of Jenkins Pipeline, as highlighted in the provided information, offers several compelling advantages for organizations and development teams:

  1. Automation: Jenkins Pipeline provides a powerful framework for automating and orchestrating the entire software delivery process. It allows you to define, manage, and execute complex workflows as code.
  2. Code-Centric: Pipelines are implemented as code and typically stored in version control repositories (e.g., Git). This code-centric approach ensures that pipeline definitions are treated like any other software artifact, enabling versioning, collaboration, and code review.
  3. Durability: Pipeline definitions are durable and can survive planned or unplanned restarts of the Jenkins controller. This resilience is essential for maintaining the integrity of your CI/CD processes.
  4. Pausable: Pipelines can be designed to pause and wait for human input or approval at specific stages. This feature is valuable for situations where manual intervention is required, such as for deploying to production environments.
  5. Versatility: Jenkins Pipelines are incredibly versatile and can support a wide range of continuous delivery requirements. Whether you need to parallelize tasks, loop through stages, or create complex branching and merging workflows, Pipelines can handle it.
  6. Extensibility: The Pipeline plugin ecosystem is extensive, and you can extend the functionality of Pipelines through custom DSL extensions and integration with various Jenkins plugins. This allows you to tailor your pipeline to meet specific project and toolchain needs.

Concept of pipeline in Jenkins:

In Jenkins, the concept of a “pipeline” refers to a series of automated steps that define the continuous integration and continuous delivery (CI/CD) process for a software project. Jenkins Pipelines are a powerful feature that allows you to model, automate, and visualize your CI/CD workflows as code. Here are some key concepts related to Jenkins Pipelines:

  • Pipeline: A pipeline is a set of instructions and stages that define the entire CI/CD process for a software project. It includes stages like code checkout, build, test, deploy, and more.
  • Declarative Pipeline: Declarative Pipelines use a structured and declarative syntax to define CI/CD workflows. They are designed to simplify pipeline creation and management, making them more accessible to users who may not be proficient in scripting.
  • Scripted Pipeline: Scripted Pipelines are written using Groovy scripting language. They offer fine-grained control and flexibility over the pipeline’s behavior. Scripted Pipelines are ideal for complex automation scenarios and advanced customization.
  • Node: A node represents a machine or agent where pipeline stages run. It can be a Jenkins agent (slave) or the Jenkins master itself. The node block is used to specify the agent for a stage in Scripted Pipelines.
  • Stage: A stage represents a specific phase or step in the CI/CD process. Typical stages include build, test, deploy, and more. Each stage can contain multiple steps executed in sequence.
  • Step: A step is a single task or command executed within a stage. Steps are the building blocks of a pipeline and can include shell commands, scripts, integrations with external tools, and more.
  • Executor: An executor is a resource (usually a thread) on a Jenkins agent that can execute a step. Executors allow parallel execution of steps within a stage.
  • Agent: An agent is a machine or environment where pipeline stages are executed. The agent block specifies where the pipeline should run, which can be any available agent or a specific node. Agents can be configured with specific tools, dependencies, and environments to perform tasks defined in the pipeline.

Approach to writing a Jenkins Pipeline:

There are two ways you can write a Jenkins pipeline.

  1. Declarative pipeline in Jenkins
  2. Scripted pipeline in Jenkins
  1. Declarative pipeline in Jenkins?

In Declarative Pipeline syntax, the pipeline block is a fundamental element that defines the entire structure and configuration of your CI/CD pipeline. The pipeline block encapsulates the entire workflow, including stages, steps, agent settings, and other pipeline-specific configurations. It provides a structured and declarative way to define your pipeline.

#1:How to write declarative pipeline in Jenkins

To write a Declarative Pipeline in Jenkins, you’ll need to use the Declarative Pipeline DSL (Domain-Specific Language) provided by Jenkins. Declarative Pipelines use a structured and simplified syntax to define CI/CD pipelines. Follow these steps to write a basic Declarative Pipeline in Jenkins:

Step #1: Log in to Jenkins: Log in to your Jenkins server or Jenkins instance

Step #2: Create a New Pipeline Job

Click on “New Item” or “New Job” on the Jenkins dashboard.

new item
  • Enter a name for your pipeline job and Select “Pipeline” and click “OK.”
select pipeline1

Step #3:Configure the Pipeline

In the pipeline configuration page: Under the “Pipeline” section, select “Pipeline script” from the dropdown. This option allows you to define your pipeline script directly.

select pipeline 2

Step #4: Write the Declarative Pipeline Script:

In the “Pipeline script” text area, you can define your Declarative Pipeline script using the structured syntax.

Here’s a basic example of Declarative pipeline Script:

pipeline {
    agent any

    stages {
        stage('Hello world') {
            steps {
                sh 'echo Hello World'
            }
        }
    }
}

In this example:

  • pipeline: This is the top-level block that defines the entire pipeline.
  • agent any: Specifies that the pipeline can run on any available agent.
  • stages: This block defines the stages of your pipeline.stage: Each stage block represents a specific phase of your CI/CD process.
  • steps: Inside each stage, you define the individual steps or commands to execute.

Customize the stages and steps to match your specific build, test, and deployment requirements.

Step #5: Save the Pipeline Configuration

Click the “Save” or “Apply” button to save the pipeline configuration.

Step #6: Run the Pipeline

  • After saving the pipeline configuration, you can manually trigger the pipeline by clicking “Build Now” on the job’s page.
  • Alternatively, you can set up triggers to automatically start the pipeline when code changes are detected in your version control system.
build now

Step #7: View Pipeline Execution

You can monitor the progress and view the logs of the pipeline execution on the job’s page. Click on the pipeline job, and then select “Console Output” to see the detailed output of each stage and step.

console output

This is a basic example of a Declarative Pipeline in Jenkins. You can customize and extend the pipeline script to suit your specific CI/CD requirements. Declarative Pipelines offer a structured and easy-to-read way to define and manage Jenkins pipelines, making them accessible to both beginners and experienced Jenkins users.

Scripted pipeline in Jenkins

In Scripted Pipeline syntax, one or more node blocks are used to define where the core work of the entire pipeline is executed. The node block specifies the machine or agent on which the enclosed steps will run. This provides fine-grained control over the execution environment and allows for more advanced customization and flexibility compared to Declarative Pipeline syntax.

#2:How to Write the Scripted Pipeline Script

To write a Scripted Pipeline in Jenkins, you’ll use Groovy scripting to define your CI/CD workflow. Here are the steps to create a basic Scripted Pipeline:

Step #1: Log in to Jenkins: Log in to your Jenkins server or Jenkins instance

Step #2: Create a New Pipeline Job

  • Click on “New Item” or “New Job” on the Jenkins dashboard.
new item 1
  • Enter a name for your pipeline job and Select “Pipeline” and click “OK.”
scripted

Step #3: Configure the Pipeline:

In the pipeline configuration page: Under the “Pipeline” section, select “Pipeline script” from the dropdown. This option allows you to define your pipeline script directly.

scripted2

Step #4: Write Your Scripted Pipeline

Inside the script block, you’ll use Groovy scripting to define your pipeline’s stages, steps, and logic. Here’s a simple example of Scripted pipeline:

node {
    stage('Hello world') {
        sh 'echo Hello World'
    }
}

In this example:

  1. node specifies the agent or node where the pipeline will run.
  2. stage defines individual stages of the pipeline (e.g., Build, Test, Deploy).
  3. echo is used to print messages to the console log.
  4. sh is used to execute shell commands.

Step #5: Save the Pipeline Configuration

Click the “Save” or “Apply” button to save the pipeline configuration.

Step #6: Run the Pipeline:

  • After saving the pipeline configuration, you can manually trigger the pipeline by clicking “Build Now” on the job’s page.
  • Alternatively, you can set up triggers to automatically start the pipeline when code changes are detected in your version control system.
scripted3

Step #7: View Pipeline Execution

You can monitor the progress and view the logs of the pipeline execution on the job’s page. Click on the pipeline job, and then select “Console Output” to see the detailed output of each stage and step.

scripted4

#3:Declarative Pipeline vs Scripted Pipeline

Declarative Pipeline and Scripted Pipeline are two syntax options in Jenkins for defining and configuring pipelines, each with its own characteristics and use cases. Let’s explore the differences between them:

Declarative Pipeline:

  1. High-Level Abstraction: Declarative Pipeline provides a higher-level abstraction for defining CI/CD pipelines. It’s designed to simplify the pipeline definition process, making it more accessible to users who are not necessarily proficient in Groovy scripting.
  2. Structured Syntax: Declarative Pipeline uses a structured and declarative syntax. You declare what you want to achieve, and Jenkins takes care of the execution flow.
  3. Limited Flexibility: While it simplifies pipeline creation, Declarative Pipeline has some limitations in terms of flexibility compared to Scripted Pipeline. It’s well-suited for most common CI/CD use cases but may not cover all edge cases.
  4. Predefined Blocks: Declarative Pipelines are organized into predefined blocks, such as pipeline, agent, stages, and steps. Users need to adhere to this structure.
  5. Ease of Use: Declarative Pipelines are easier to read and understand, especially for those new to Jenkins or CI/CD automation.
  6. Built-In Error Checks: Declarative Pipelines include built-in error-checking and validation, making it less prone to certain types of coding errors.

Scripted Pipeline:

  1. Lower-Level Control: Scripted Pipeline offers more fine-grained control over the pipeline’s behavior and execution flow. It allows you to write custom Groovy scripts to define pipeline logic.
  2. Scripting Flexibility: You have full control over the pipeline script, which means you can implement complex and customized workflows.
  3. Complexity: Scripted Pipeline can become complex and harder to read for beginners or those unfamiliar with Groovy scripting.
  4. Script Blocks: Instead of predefined blocks, Scripted Pipelines primarily consist of script blocks where you write Groovy code.
  5. Greater Learning Curve: Due to its flexibility and the need for Groovy scripting knowledge, Scripted Pipeline has a steeper learning curve.
  6. Extensive Customization: Scripted Pipelines are suitable for scenarios where you need extensive customization or integration with external tools and services.

Conclusion:

In this article we have covered How to write Jenkins pipeline, why pipeline in Jenkins, Concept of pipeline in Jenkins, Approach to writing a Jenkins Pipeline and Declarative Pipeline vs Scripted Pipeline.

Related Articles:

How to Install Jenkins on Ubuntu 22.04 LTS

Reference:

Jenkins Pipeline official page

About Priti Adkine

I am Priti Adkine working as Software Engineer and having 1+ years of Experience. Likes to share knowledge.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share via
Copy link