Wednesday, 3 April 2024

Pipelines & Jenkinsfile in Jenkins

1. What to use Pipelines & Jenkinsfile for?

A Pipeline is a series of automated executed job steps, is used to automate CICD (build, test, deploy, report)

- A Jenkinsfile is a text file, is used to define a Jenkins Pipeline.

2. How to use Pipelines & Jenkinsfile?

- Create a Pipeline is create a job in Jenkins >> see more: Create a Pipeline

- Jenkinsfile syntax:

pipeline {
    agent none
options {
timeout(time: 1, unit: 'HOURS') // Sets a timeout limit for the pipeline
retries(2) // Retries the pipeline 2 times in case of failure
buildDiscarder(logRotator(numToKeepStr: '5')) // Keeps the logs of the last 5 builds
  environment {
MY_VARIABLE = "someValue" // Define a simple environment variable
PASSWORD = credentials('my-credential-id') // Safely inject a password from Jenkins credentials
}
    stages {
stage('Advanced Script') {
steps {
script {
// Your Groovy code here
                   echo "Environment variable is $MY_VARIABLE"
}
}
        stage('Build') {
            agent any 
            steps {
                // Steps to build the application
                echo 'This is Build stage.'
            }
        }
        stage('Test') {
            agent { 
                label 'linux-server-test' 
            
            steps {
                // Steps to Test the application
            }
            post { 
                always { 
                    echo 'Test on linux-server-test finished.'
                
            }
        }
        stage('Deploy') {
            agent { 
                label 'linux-server-deploy' 
            
            steps {
                // Steps to Deploy the application
            }
            post { 
                always { 
                    echo 'Deploy on linux-server-deploy finished.'
                
            }
        }
    }
    post {
        always {
            echo 'This message will always be printed.'
        }
        success {
            echo 'This message will only be printed if the pipeline succeeds.'
        }
        failure {
            echo 'This message will only be printed if the pipeline fails.'
        }
    }
}  

Explain:
+ pipeline: define main pipeline
+ agent: specifies agent stages will be executed
+ option: to change default behavior of Jenkins pipeline
+ environment: define variables for using by all stages, steps, script in pipeline.
+ stages: define stages of pipeline
+ stage: define a specific stage
+ steps: contents steps to perform work in stage
+ script: to using Groovy code in pipeline
+ post: define actions or steps that are executed at the end of pipeline
+ always: steps are executed after every run of pipeline
+ success: steps are executed only if pipeline completes success
+ failure: steps are executed only if pipeline fails 

Reference
- https://www.jenkins.io/doc/book/pipeline/jenkinsfile/

Thank you.

No comments:

Post a Comment

Golang Advanced Interview Q&A