top of page

Jenkins-Day-5

### Project: Configuring Pipeline as Code in Jenkins GUI


This project outlines the steps to create a pipeline in Jenkins using "Pipeline as Code" with three stages: Compile, Test, and Package. The pipeline script will output a message at each stage.



### 1. Search for Pipeline Plugin

Explanation: Ensure that Jenkins is ready to support pipelines by installing the required plugin.

- Go to Jenkins Dashboard -> Manage Jenkins -> Manage Plugins.

- Under the Available tab, search for Pipeline.

- Check the box next to Pipeline and click Install without restart.


### 2. Install Plugin: Pipeline Multibranch

Explanation: Enable support for multibranch pipelines & Pipeline stage view if necessary.

- In Manage Jenkins -> Manage Plugins, search for Pipeline Multibranch & Pipeline stage view.

- Install Pipeline: Multibranch & stage view. plugin by checking the box and clicking Install without restart.


### 3. Create a Job with Pipeline Type

Explanation: Set up a new Jenkins job that supports pipeline configuration.

- Go to the Jenkins Dashboard.

- Click on New Item.

- Enter the job name (e.g., `pipeline-project`).

- Select Pipeline as the project type.

- Click OK to create the job.


### 4. Create a Pipeline Script

Explanation: Define a pipeline script with three stages: Compile, Test, and Package.

- In the job configuration page, scroll down to the Pipeline section.

- Choose Pipeline Script.

- Enter the following script in the pipeline script box:


pipeline {

agent any


stages {

stage('Compile') {

steps {

echo 'Compiling the source code...'

}

}

stage('Test') {

steps {

echo 'Running the tests...'

}

}

stage('Package') {

steps {

echo 'Packaging the application...'

}

}

}

}


- Click Save.


### 5. Run the Pipeline Job

Explanation: Trigger the pipeline execution manually.

- Go to the Project Dashboard of the newly created pipeline.

- Click Build Now to start the pipeline.

- You should see the stages run in sequence: Compile, Test, and Package, with each stage echoing its name.


### 6. Validate the Pipeline Execution

Explanation: Confirm that each stage in the pipeline has executed successfully.

- After the build completes, click on the build number in the Build History.

- Check the Console Output to see the echo messages for each stage:

- Compiling the source code...

- Running the tests...

- Packaging the application...


### Summary:

- Installed necessary pipeline plugins.

- Created a Jenkins pipeline job.

- Configured a basic pipeline script with three stages.

- Validated the output of each stage via console logs.


Groovy Code

Detailed Explanation

pipeline {

agent any


stages {

stage('Compile') {

steps {

echo 'Compiling the source code...'

}

}

stage('Test') {

steps {

echo 'Running the tests...'

}

}

stage('Package') {

steps {

echo 'Packaging the application...'

}

}

}

}

1. `pipeline {`

- This defines the start of a Jenkins pipeline block. The entire structure of the pipeline (stages, steps, and configuration) will go inside this block.


2. `agent any`

- Specifies that the pipeline can be executed on any available Jenkins agent (node). This means Jenkins will choose any node in the cluster to run the pipeline unless you specify a specific node label or agent.


3. `stages {`

- The stages block is used to define multiple stages in the pipeline. Each stage represents a logical phase in the pipeline, such as compilation, testing, or packaging.


4. `stage('Compile') {`

- Defines a stage in the pipeline named Compile. This is the first stage of the pipeline where the code will be compiled.

- The name inside `stage('...')` is the name that will appear in the Jenkins UI when the pipeline is executed.


5. `steps {`

- Inside each stage, the steps block defines the actual commands or tasks to execute for that stage. In a real-world scenario, this could involve running shell commands or invoking specific build tools.


6. `echo 'Compiling the source code...'`

- `echo` is a Jenkins Pipeline step that outputs text to the console. This line will print "Compiling the source code..." when the pipeline reaches the Compile stage.

- It serves as a simple placeholder for a real compilation step.


7. `stage('Test') {`

- This defines the second stage named Test. This stage will be responsible for running the tests on the source code.


8. `steps {`

- The steps block for the Test stage, just like in the Compile stage, defines the actions to take during the testing phase.


9. `echo 'Running the tests...'`

- This command will print "Running the tests..." to the console when the pipeline is running the Test stage.

- Again, in a real scenario, this could be replaced by actual test commands (e.g., running unit tests).


10. `stage('Package') {`

- This defines the third stage called Package, where the source code is packaged (for example, into a .jar or .war file).


11. `steps {`

- The steps block for the Package stage, where actions related to packaging are defined.


12. `echo 'Packaging the application...'`

- This will print "Packaging the application..." to the console when the pipeline runs the Package stage.

- In a real-world case, this would be replaced by commands to package the application.


13. `}`

- Closes the respective blocks for steps, stage, and pipeline. Every block opened with `{` needs a closing `}`.

 

### Project: Jenkins Pipeline with "Pipeline Script from SCM"


This project demonstrates how to set up a Jenkins pipeline by fetching a Jenkinsfile from a GitHub repository. This setup allows Jenkins to automatically pull the pipeline script and run it directly from the source control.


### Scenario:

You need to create a Jenkins pipeline using the "Pipeline Script from SCM" option, where the Jenkinsfile is stored in a GitHub repository.


#### 1. Create a New Jenkins Pipeline Job


- Explanation: Open Jenkins and create a new pipeline job that will run based on the Jenkinsfile from a GitHub repository.

- Action:

- Navigate to Jenkins dashboard.

- Click on `New Item`.

- Enter a name for your project (e.g., "GitHub-Pipeline-Job").

- Select `Pipeline` and click `OK`.


#### 2. Configure the Pipeline to Use "Pipeline Script from SCM"


- Explanation: Specify that the pipeline script (Jenkinsfile) will be retrieved from SCM, in this case, GitHub.

- Action:

- Scroll down to the `Pipeline` section.

- In the `Definition` dropdown, select `Pipeline script from SCM`.

- In the `SCM` dropdown, choose `Git`.


#### 3. Set Up GitHub Repository Details


- Explanation: Provide the GitHub repository URL where the Jenkinsfile is located.

- Action:

- In the `Repository URL`, enter the URL of the GitHub repository (e.g., `https://github.com/username/repository.git`). or https://github.com/preethid/addressbook.git

- If your repository is private, add credentials by clicking the `Add` button and configuring the credentials for GitHub access.

#### 4. Configure the Branch and Jenkinsfile Path


- Explanation: Specify the branch and the location of the Jenkinsfile in the repository.

- Action:

- In the `Branch Specifier` field, specify the branch name (e.g., `*/main` or `*/master`).

- Under `Script Path`, provide the location of the Jenkinsfile in the repository (e.g., `Jenkinsfile` if it's located in the root of the repo, or `folder-name/Jenkinsfile` if it's nested).


#### 5. Configure Build Triggers (Optional)


- Explanation: Optionally, configure how often the pipeline should trigger (e.g., on changes to SCM or scheduled builds).

- Action:

- Scroll to `Build Triggers`.

- Select `Poll SCM` if you want the job to run automatically when changes are pushed to GitHub.

- Define the polling schedule in cron syntax (e.g., `H/5 * * * *` to poll every 5 minutes).


#### 6. Save the Job


- Explanation: Save the job configuration.

- Action:

- Click `Save` at the bottom of the page.


#### 7. Run the Pipeline Job


- Explanation: Manually trigger the job to validate if it fetches the Jenkinsfile from the GitHub repository and runs successfully.

- Action:

- Click `Build Now` to trigger the job manually.

- Monitor the build by clicking on the `Console Output` of the running build.


#### 8. Validate the Pipeline Execution


- Explanation: Validate that the pipeline executed the stages defined in the Jenkinsfile fetched from the GitHub repository.

- Action:

- Check the console logs to ensure that each stage (Compile, Test, Package, etc.) runs as defined in the Jenkinsfile.

- Ensure no errors occurred during the build process.


By following these steps, you will have a fully functioning Jenkins pipeline, pulling and executing a Jenkinsfile from a GitHub repository.


 

### Project: Jenkins Pipeline with Git Branch and Parameters


This project guides you through creating a Git branch, cloning a repository, adding a Jenkinsfile with stages and parameters, pushing the changes to GitHub, and setting up a Jenkins pipeline to run using the Jenkinsfile from SCM.


### Scenario:

You need to create a Git branch, clone a repository, add a Jenkinsfile with `dev`, `test`, and `prod` stages, define parameters, push the changes to GitHub, and configure Jenkins to execute the pipeline using the "Pipeline script from SCM" feature.


#### 1. Create a New Git Branch (`feature/devops_1`)


- Explanation: Create a new branch for the development work.

- Command:


git clone https://github.com/preethid/addressbook.git

cd addressbook

git checkout -b feature/devops_1


#### 2. Create the Jenkinsfile with 3 Stages and Parameters


- Explanation: Create a `Jenkinsfile` with stages for development, testing, and production, and include a parameters block to define input parameters.

- Action:

- Open your text editor Example VIM, and create a new `Jenkinsfile` with the following content:

vim jenkinsfile

pipeline {

    agent any


    parameters {

        string(name: 'ENVIRONMENT', defaultValue: 'dev', description: 'Environment to deploy to')

        booleanParam(name: 'RUN_TESTS', defaultValue: true, description: 'Run tests?')

        choice(name: 'DEPLOY_SERVER', choices: ['dev', 'test', 'prod'], description: 'Choose deployment server')

    }


    stages {

        stage('Dev Stage') {

            steps {

                script {

                    if (params.ENVIRONMENT == 'dev') {

                        echo "Building for development environment"

                    }

                }

            }

        }

        stage('Test Stage') {

            steps {

                script {

                    if (params.RUN_TESTS) {

                        echo "Running tests in the ${params.ENVIRONMENT} environment"

                    } else {

                        echo "Skipping tests"

                    }

                }

            }

        }

        stage('Prod Stage') {

            steps {

                script {

                    if (params.DEPLOY_SERVER == 'prod') {

                        echo "Deploying to production server"

                    } else {

                        echo "Deploying to ${params.DEPLOY_SERVER} server"

                    }

                }

            }

        }

    }

}


- Explanation:

- Parameters:

- `ENVIRONMENT`: Defines the environment (default: dev).

- `RUN_TESTS`: Boolean parameter to decide whether to run tests.

- `DEPLOY_SERVER`: A choice parameter to specify which server to deploy to (dev, test, or prod).

- Stages:

- Dev Stage: Simulates development environment build.

- Test Stage: Runs tests based on the parameter.

- Prod Stage: Deploys to the selected server.


#### 3. Push the Changes to GitHub (`feature/devops_1`)


- Explanation: Push the Jenkinsfile and the changes to your Git branch.

- Commands:


git add Jenkinsfile

git commit -m "Added Jenkinsfile with stages and parameters"

git push origin feature/devops_1



#### 4. Create a New Jenkins Pipeline with "Pipeline Script from SCM"


- Explanation: In Jenkins, create a new pipeline job that pulls the Jenkinsfile from the `feature/devops_1` branch in the GitHub repository.

- Steps:

- In Jenkins, navigate to the dashboard and click `New Item`.

- Name your pipeline (e.g., "Addressbook-Pipeline"), select `Pipeline`, and click `OK`.

- Scroll down to the `Pipeline` section, and under `Definition`, select `Pipeline script from SCM`.

- Under `SCM`, choose `Git`.

- In the `Repository URL` field, enter `https://github.com/preethid/addressbook.git`.

- In the `Branch Specifier`, enter `*/feature/devops_1`.

- In the `Script Path`, enter `Jenkinsfile`.

- Click `Save`.


#### 5. Build the Pipeline


- Explanation: Manually trigger the pipeline and provide values for the defined parameters.

- Steps:

- After saving the pipeline configuration, click `Build with Parameters` in the Jenkins project.

- Enter values for `ENVIRONMENT`, `RUN_TESTS`, and `DEPLOY_SERVER` parameters.

- Click `Build`.


#### 6. Validate the Build Stages


- Explanation: Verify that each stage (`dev`, `test`, and `prod`) runs as expected based on the parameter values you provided.

- Steps:

- Monitor the `Console Output` to check that the stages execute correctly.

- Verify that the `Dev Stage`, `Test Stage`, and `Prod Stage` print the expected messages based on the parameter inputs.




### Summary:


- Created a new Git branch: `feature/devops_1`.

- Cloned the repository and added a Jenkinsfile with 3 stages: `dev`, `test`, and `prod`.

- Defined parameters for environment, running tests, and deployment servers.

- Pushed the changes to the `feature/devops_1` branch.

- Configured a Jenkins pipeline with "Pipeline script from SCM" to fetch the Jenkinsfile from GitHub.

- Ran the pipeline with parameters and validated the stages.


By following these steps, you will have a fully configured Jenkins pipeline with parameters and multiple stages, using the Jenkinsfile stored in GitHub.


 

###line-by-line explanation of the code from the `Jenkinsfile`:


pipeline {

agent any


**pipeline**: Defines the Jenkins pipeline.

**agent any**: Runs the pipeline on any available Jenkins agent.



parameters {

string(name: 'ENVIRONMENT', defaultValue: 'dev', description: 'Environment to deploy to')

booleanParam(name: 'RUN_TESTS', defaultValue: true, description: 'Run tests?')

choice(name: 'DEPLOY_SERVER', choices: ['dev', 'test', 'prod'], description: 'Choose deployment server')

}


**parameters**: Declares input parameters for the pipeline.

**string(...)**: Defines a string parameter called `ENVIRONMENT` with a default value of 'dev'.

**booleanParam(...)**: Defines a boolean parameter `RUN_TESTS` with a default value of `true`.

**choice(...)**: Defines a choice parameter `DEPLOY_SERVER` with options: 'dev', 'test', 'prod'.



stages {

stage('Dev Stage') {

steps {

script {

if (params.ENVIRONMENT == 'dev') {

echo "Building for development environment"

}

}

}

}


**stages**: Defines multiple stages of the pipeline.

**stage('Dev Stage')**: Defines the first stage, "Dev Stage".

**steps**: Contains the commands or actions to execute in this stage.

**script { ... }**: A block for executing script logic.

**if (params.ENVIRONMENT == 'dev')**: Checks if the `ENVIRONMENT` parameter is 'dev'.

**echo "Building for development environment"**: Prints a message indicating the development environment build.



stage('Test Stage') {

steps {

script {

if (params.RUN_TESTS) {

echo "Running tests in the ${params.ENVIRONMENT} environment"

} else {

echo "Skipping tests"

}

}

}

}


**stage('Test Stage')**: Defines the second stage, "Test Stage".

**if (params.RUN_TESTS)**: Checks if the `RUN_TESTS` parameter is true.

**echo "Running tests..."**: Prints a message indicating that tests are being run.

**else**: Executes the next block if the `RUN_TESTS` parameter is false.

**echo "Skipping tests"**: Prints a message if tests are skipped.



stage('Prod Stage') {

steps {

script {

if (params.DEPLOY_SERVER == 'prod') {

echo "Deploying to production server"

} else {

echo "Deploying to ${params.DEPLOY_SERVER} server"

}

}

}

}

}

}

**stage('Prod Stage')**: Defines the third stage, "Prod Stage".

**if (params.DEPLOY_SERVER == 'prod')**: Checks if the `DEPLOY_SERVER` parameter is set to 'prod'.

**echo "Deploying to production server"**: Prints a message if deploying to production.

**else**: Executes the next block if `DEPLOY_SERVER` is not 'prod'.

**echo "Deploying to ${params.DEPLOY_SERVER} server"**: Prints a message indicating the chosen deployment server.



 

project outline for creating a Jenkins pipeline that uses "Pipeline script from SCM" with WHEN conditions based on selected environments:


### Project: Environment-Based Jenkins Pipeline


#### Scenario

We have three environments: Production, Development, and Test. Based on the selected environment, a specific message will be printed.


1. Create a Git Repository:

- Create a new Git repository (e.g., `env-pipeline`) on GitHub or your preferred Git service.

- Clone the repository to your local machine.

git clone https://github.com/yourusername/env-pipeline.git

cd env-pipeline

2. Create a Jenkinsfile:

- Create a `Jenkinsfile` in the repository with the following content:



pipeline {

agent any

parameters {

choice(name: 'ENVIRONMENT', choices: ['Production', 'Development', 'Test'], description: 'Select the environment')

}


stages {

stage('Production') {

when {

expression { params.ENVIRONMENT == 'Production' }

}

steps {

echo 'Code Deployed in Production environment!'

}

}


stage('Development') {

when {

expression { params.ENVIRONMENT == 'Development' }

}

steps {

echo 'Code Deployed in Development environment!'

}

}


stage('Testing') {

when {

expression { params.ENVIRONMENT == 'Test' }

}

steps {

echo 'Code Deployed in Test environment!'

}

}

}

}



3. Push the Jenkinsfile to GitHub:

- Add, commit, and push the `Jenkinsfile` to your Git repository.

git add Jenkinsfile

git commit -m "Add Jenkinsfile for environment-based pipeline"

git push origin main


4. Create a New Pipeline Job in Jenkins:

- Open your Jenkins dashboard.

- Click on "New Item".

- Enter a name for the job (e.g., `Environment-Pipeline`).

- Select "Pipeline" and click "OK".


5. Configure the Pipeline Job:

- Scroll down to the "Pipeline" section.

- Set "Definition" to "Pipeline script from SCM".

- Choose "Git" as the SCM.

- Enter the repository URL (e.g., `https://github.com/yourusername/env-pipeline.git`).

- Set the branch to `main` (or the appropriate branch).

- Click "Save".


6. Run the Job:

- Click "Build with Parameters" on the left side of the job page.

- Select the environment (Production, Development, or Test) from the dropdown.

- Click "Build".


7. Validate the Output:

- Once the job completes, click on the build number (e.g., #1) to view the details.

- Check the console output to see the printed message corresponding to the selected environment.


### Validation Steps

- Confirm that the Jenkins job runs successfully.

- Ensure the correct message is displayed in the console output based on the selected environment.


### Summary

This project demonstrates how to create a Jenkins pipeline that selects actions based on a specified environment using parameters and conditions. Each selected environment triggers a different message to be printed in the build logs.


 

####Create a Jenkins pipeline with "pipeline script from SCM" using "when" and "input" directives. The pipeline will ask for input to choose between Production, Development, or Test environments and display a corresponding message for the selected environment.


### Scenario:

We have three environments: Production, Development, and Test. The pipeline will prompt for environment selection, and based on that input, it will print a message for the chosen environment.


#### 1. Create a Git Repository:

- Create a new Git repository (e.g., `ENV-pipeline`) on GitHub or your preferred Git service.

- Clone the repository to your local machine.


git clone https://github.com/yourusername/ENV-pipeline.git

cd ENV-pipeline

2. Create a Jenkinsfile:

- Create a `Jenkinsfile` in the repository with the following

Add the following content to the `Jenkinsfile`:


pipeline {

agent any


stages {

stage('Input Environment') {

steps {

script {

env.SELECTED_ENV = input(

id: 'EnvironmentInput',

message: 'Select the environment to proceed',

parameters: [

choice(name: 'ENVIRONMENT', choices: ['Production', 'Development', 'Test'], description: 'Choose the environment')

]

)

}

}

}


stage('Production Environment') {

when {

expression { env.SELECTED_ENV == 'Production' }

}

steps {

echo 'You have selected the Production environment!'

}

}


stage('Development Environment') {

when {

expression { env.SELECTED_ENV == 'Development' }

}

steps {

echo 'You have selected the Development environment!'

}

}


stage('Test Environment') {

when {

expression { env.SELECTED_ENV == 'Test' }

}

steps {

echo 'You have selected the Test environment!'

}

}

}

}



#### 3. Push the Jenkinsfile to GitHub:

- Add, commit, and push the `Jenkinsfile` to your Git repository.


git add Jenkinsfile

git commit -m "Add Jenkinsfile for ENVironment-based pipeline"

git push origin main


#### 4. Create a New Pipeline Job in Jenkins:

- Open your Jenkins dashboard.

- Click on "New Item".

- Enter a name for the job (e.g., `ENVironment-Pipeline`).

- Select "Pipeline" and click "OK".


Configure the Pipeline Job:

- Scroll down to the "Pipeline" section.

- Set "Definition" to "Pipeline script from SCM".

- Choose "Git" as the SCM.

- Enter the repository URL (e.g., `https://github.com/yourusername/ENV-pipeline.git`).

- Set the branch to `main` (or the appropriate branch).

- Click "Save".


#### 5. Run the Pipeline


- Build the Pipeline:

- Go to the project and click "Build Now".

- Jenkins will prompt for environment input. Choose between "Production", "Development", or "Test" and click "Proceed".


#### 6. Validate the Output


- After running the pipeline, check the console output. It should display the message based on the environment you selected.


#### Summary:

This project uses the "when" directive and the "input" directive in a Jenkins pipeline to prompt the user for environment selection. Depending on the input, the corresponding environment message is printed. The pipeline script is stored in SCM (GitHub), and Jenkins pulls the script from the repository to run it.


 

###Explanation of each line of the provided Jenkins pipeline script:


pipeline {


- pipeline: This starts the definition of the Jenkins pipeline. It contains the entire workflow configuration.


agent any


- agent any: This directive specifies that the pipeline can run on any available Jenkins agent.



stages {


- stages: Defines a block that contains multiple stages within the pipeline. Each stage represents a step in the pipeline process.



stage('Input Environment') {


- stage('Input Environment'): Defines the first stage called 'Input Environment'. A stage is a step in the pipeline that performs a specific task.



steps {


- steps: The steps block defines what actions are to be performed in this stage.



script {


- script: Allows running Groovy code inside a declarative pipeline. This is used when you need to write more complex logic inside the pipeline.



env.SELECTED_ENV = input(


- env.SELECTED_ENV = input(...): This assigns the result of an input prompt to the environment variable `SELECTED_ENV`.



id: 'EnvironmentInput',


- id: A unique identifier for the input step to help Jenkins track it.



message: 'Select the environment to proceed',


- message: The message shown to the user during the input prompt, asking them to select the environment.



parameters: [

choice(name: 'ENVIRONMENT', choices: ['Production', 'Development', 'Test'], description: 'Choose the environment')

]


- parameters: Defines the parameters for the input step. In this case, a choice parameter is used.

- choice(...): This creates a dropdown list of choices ('Production', 'Development', 'Test') for the user to select from.



)


- ): This closes the `input()` function.



}

}

}


- Closing script, steps, and stage: These lines close the respective blocks.



stage('Production Environment') {


- stage('Production Environment'): Defines the next stage, which handles the actions specific to the 'Production' environment.



when {

expression { env.SELECTED_ENV == 'Production' }

}


- when: Conditional block that controls the execution of the stage. This stage will run only if the specified condition is true.

- expression { env.SELECTED_ENV == 'Production' }: This checks if the selected environment is 'Production'.



steps {

echo 'You have selected the Production environment!'

}


- steps { echo 'You have selected the Production environment!' }: Prints a message to the Jenkins console stating that 'Production' has been selected.



}


- }: Closes the stage for the 'Production' environment.



stage('Development Environment') {

when {

expression { env.SELECTED_ENV == 'Development' }

}

steps {

echo 'You have selected the Development environment!'

}

}


- stage('Development Environment'): Similar to the 'Production Environment' stage, but it checks if the environment selected is 'Development'.

- when { expression { env.SELECTED_ENV == 'Development' } }: This stage will run only if 'Development' is selected.

- steps { echo 'You have selected the Development environment!' }: Prints a message for the Development environment.



stage('Test Environment') {

when {

expression { env.SELECTED_ENV == 'Test' }

}

steps {

echo 'You have selected the Test environment!'

}

}

}

}


- stage('Test Environment'): Similar to the previous stages but for the 'Test' environment.

- when { expression { env.SELECTED_ENV == 'Test' } }: This stage runs only if 'Test' is selected.

- steps { echo 'You have selected the Test environment!' }: Prints a message stating the Test environment is selected.


### Summary:

- The pipeline asks the user to choose an environment (Production, Development, or Test).

- Based on the user’s selection, the appropriate stage is triggered, and a message is printed to the console.

- Conditional stages are implemented using the `when` directive with an `expression` block.


 


bottom of page