Thursday, August 31, 2023

Jenkins Pipeline

 Jenkins Pipeline

Pipeline As Code

About Me

Lots of Engineers aspire to be full-stack, but I don't. I aspire to be a T-Shaped Engineer.

Hi there👋

I am Abid-Moon (GitHub), a DevOps Consultant from ðŸ‡®ðŸ‡³ with 2+ years of experience focusing majorly on Continous Integration, Continous Deployment, continuous monitoring and process development which includes code compilation, packaging , deployment/release and monitoring.🎯

I mostly work with CI/CD Setup, Cloud Services, Developing Automation & SRE tools and AI/MLops.🚀

Pipeline script
• Another way of job configurartion with help of code

Advantages:

  • Can divide the jobs into parts (build /test /deploy/..) & each part can run in each agent.

  • Parallel execution of stages are easy configure so that we can save time

  • Each stage can execute with different version of JDK/MVN versions

  • Can retrigger from failed stage

  • visualize the build flow

  • Build can hold for user input(specific user can eneter, explain LDAP concept)

  • Version control,code review

  • pause, restart the build

  • In multibranch pipeline scripts will automatically create in sunbranches

    Types of Pipeline
    • Declarative

    • scripted
    Difference between Declarative and scripted

  • Declarative pipeline is a recent addition.

  • More simplified and opinionated syntax when compared to scripted Declarative syntax

    pipeline { agent any

    stages { stage('Build') {

    steps { //

    } }

    stage('Test') { steps {

    // }

    }
    stage('Deploy') {

    steps { //

    } }

    } }

Introduction

Jenkins Pipeline by abid-moon

Scripted Syntax

node { stage('Build') {

// }

stage('Test') { //

}
stage('Deploy') {

// }

}

PIPELINE BASIC

Steps

  • We need to write step inside the stage directive

  • steps contains (command/scripts) that we used in the build

  • One steps directive should be there in stage directive

    Stage

  • Define particular stage (build/test/deploy/..) of our job

  • atleast one stage has to be there

  • name will be display on the jenkins dashboard

    stages

  • contains sequence of stages

  • atleast one stage has tobe there Agent

  • where (master/slave/container..)we need to run our pipeline script

    Stage colors

  • White (stage is not executed )

  • Green (stage is success)

  • Blue lines (stage is executing)

  • Redlines or red line (stage is failed)

  • Red (fews stage success, any one is failed, few remain sucess stage will show red )

Jenkins Pipeline by abid-moon

Comments
Single line comment : //

Multiline comment: /* ==============

*/

Simple Hello world pipeline:

pipeline{ agent any

stages{ stage('Hello_world'){

steps{
echo 'Hello world'

} }

} }

O/P

Batch commands

Jenkins Pipeline by moon

pipeline{ agent any

stages{ stage('batch'){

steps{
bat "dir"

bat "cd"

bat "ping www.google.com" }

} }

} O/P

Multiline bat command

pipeline{ agent any

stages{ stage('batch'){

steps{ bat """

dir
cd
ping www.google.com

"""

} }

} }

O/P

Jenkins Pipeline by moon

What is variable?
Variable is used to store the value.

<variable name> = <variable value> Types

  • Predefined variable

  • User variable

    Predefined: http://localhost:8080/env-vars.html

VARIABLES

Jenkins Pipeline by

Predefined

pipeline{ agent any

stages{ stage('pre'){

steps{
echo " predefined variable $BUILD_NUMBER

} }

} }

$WORKSPACE "

Userdefined : variable we can define in rootlevel or stage level pipeline{

agent any

} stages{

stage('User'){ steps{

echo " userdefined variable $MYHOME " }

} }

}

environment{

MYHOME="Chennai"

Jenkins Pipeline by

User defined variables in

  • Global level

  • stage level

  • script level

    Global level

    pipeline{ agent any

    environment{ MYHOME="KASHMIR"

    } stages{

    stage('User'){ steps{

    echo " userdefined variable $MYHOME " }

    } }

    }

    Stage level

    pipeline{ agent any

    stages{

    stage('User'){ environment{

    MYHOME="KASHMIR" }

    steps{
    echo " userdefined variable $MYHOME "

    } }

    } }

Jenkins Pipeline by Kalaiarasan

Script level

pipeline{ agent any

stages{ stage('User'){

steps{

} }

} }

pipeline{ agent any

stages{ stage('User'){

} }

} }

Scope of the Variables : priority order first (script),second(stage),third(global or root)

if you defined the same varaible in global ,stage and , it will pick up stage.

pipeline{ agent any

stages{ stage('User'){

script{

}

MYHOME="KASHMIR"

}

echo " userdefined variable $MYHOME "

steps{

script{

MYHOME="KASHMIR"

echo " userdefined variable $MYHOME "

environment{

MYHOME="KASHMIR"

}

environment{

MYHOME="thiruverkadu"

Jenkins Pipeline by Kalaiarasan

}

steps{
echo " userdefined variable $MYHOME "

} }

} }

O/P

Predefined vs user defined values:

if you defined diff values in variable , we can call above stage variable by ${env.variablename}

pipeline{ agent any

environment{ MYHOME="KASHMIR"

} stages{

stage('User'){ environment{

MYHOME="BAGHAT" }

steps{ script{

MYHOME="chen" }

echo " userdefined variable $MYHOME previous variable ${env.MYHOME} " }

} }

}

10 Jenkins Pipeline by Kalaiarasan

Eventhough it predefined variable if we change for custom, priority for user defined

pipeline{ agent any

environment{ BUILD_NUMBER="KASHMIR"

} stages{

stage('User'){ environment{

MYHOME="BAGHAT" }

steps{ script{

MYHOME="chen" }

echo " used predefined variable $BUILD_NUMBER " }

} }

}

Diff B/W Single and Double quotes

if we defined in single quote it will take as string

11 Jenkins Pipeline by MOON

If we defined in double quotes, it will take as variable name

Concatenate

process of combining two or more string by '+' operator in jenkins

pipeline{ agent any

environment{ name1="kalai"

name2='arasan' }

stages{ stage('concatenate'){

steps{ script{

Name= name1 + name2 }

echo " concatenate $Name" }

} }

}

12 Jenkins Pipeline by

Syntax:

PARAMETERS

$VARIALENAME and params. VARIALENAME is same.

pipeline{ agent any

parameters {
string(name: 'DEPLOY_ENV', defaultValue: 'staging', description: '')

text(name: 'DEPLOY_TEXT', defaultValue: 'One\nTwo\nThree\n', description: '')

booleanParam(name: 'TOGGLE', defaultValue: true, description: 'Toggle this value') choice(name: 'CHOICE', choices: ['One', 'Two', 'Three'], description: 'Pick something') file(name: 'FILE', description: 'Some file to upload')
password(name: 'PASSWORD', defaultValue: 'SECRET', description: 'A secret password')

13 Jenkins Pipeline by

}

stages{ stage('string'){

steps{
echo " string $DEPLOY_ENV"

} }

steps{
echo " text $DEPLOY_TEXT"

} }

stage('booleanParam'){ steps{

script{ if(TOGGLE){

echo " now execute, booleann is true" }else{

} }

stage('text'){

} }

steps{

} }

steps{
echo " file $FILE"

} stage('choice'){

} stage('file'){

echo " Dont execute, boolean is true" }

script{
if(DEPLOY_ENV=='staging'){

echo " choice $CHOICE" }

stage('password'){

steps{
echo " password $PASSWORD"

} }

} }

O/P

14 Jenkins Pipeline by

Dryrun

Dryrun is mainly used for first time of parameter build, before getting build with parameter.

Options stage level or pipe level

  • Retry: before failing the job, will run the job again to specified times

  • buildDiscarder : used to delete old build logs in number or days

  • disableConcurrentBuilds: used to disable concurrent build

OPTION SET

15 Jenkins Pipeline by

  • Timeout:Time set for particular build

  • timestamp: will add the time to the build process Retry Stage based
    pipeline {

    agent any stages {

    stage('Deploy') { options {

    retry(3)
    timeout(time: 5, unit: 'SECONDS')

    } steps {

    sh 'echo hello' sleep(10)

    } }

    } }

    Retry: step based

    pipeline { agent any

    stages { stage('Deploy') {

    steps { retry(3) {

    sh 'echo hello' }

    } }

    } }

    Retry: global based

    pipeline { agent any

    options{ retry(3)

    }
    stages {

    stage('Deploy') {

16 Jenkins Pipeline by

steps {
sh 'echo hello'

} }

} }

if any eror or timeout it will execute 3 times

buildDiscarder

  • numbers: options { buildDiscarder(logRotator(numToKeepStr: '5')) }

  • days: options {buildDiscarder(logRotator(daysToKeepStr: '7'))} )

    pipeline { agent any

    options { buildDiscarder(logRotator(numToKeepStr: '5')) }

    stages { stage('Deploy') {

    steps {
    sh 'echo hello'

    } }

    } }

    before : buildDiscarder execution

17 Jenkins Pipeline by

After : buildDiscarder execution

disableConcurrentBuilds

if execute the build if it takes time to complete again paralley , we trigger b4 complete the previous build, again build get start to execute, due to this job will get conflicts with nodes.

pipeline { agent any

options { buildDiscarder(logRotator(numToKeepStr: '5')) disableConcurrentBuilds()

} stages {

stage('Deploy') { steps {

sh 'echo hello'

} }

} }

sleep(10)

18 Jenkins Pipeline by ABID MOON

Timeout:

timeout(time: 30, unit: 'MINUTES') timeout(time: 30, unit: 'SECONDS') timeout(time: 30, unit: 'HOURS')

Syntax

pipeline { agent any

options { buildDiscarder(logRotator(numToKeepStr: '5')) disableConcurrentBuilds()
timeout(time: 5, unit: 'SECONDS')

} stages {

stage('Deploy') { steps {

sh 'echo hello' sleep(10)

} }

} }

its aborted after the timelimit

19 Jenkins Pipeline by ABID MOON

Timeout Stage based:

pipeline { agent any

stages { stage('Deploy') {

options { retry(3)

timeout(time: 5, unit: 'SECONDS')

} steps {

sh 'echo hello'

} }

} }

Timestamp:

pipeline { agent any

sleep(10)

options { buildDiscarder(logRotator(numToKeepStr: '5')) disableConcurrentBuilds()
timestamps()

} stages {

stage('Deploy') { steps {

sh 'echo hello' sleep(2)

sh 'echo hi' sleep(2)

20 Jenkins Pipeline by

sh 'echo how' }

} }

}
With timestamp

Without timestamp

21 Jenkins Pipeline by

Trigger Other Jobs

• we used build('jobname') option syntax

pipeline { agent any

stages { stage('triggerjob') {

steps {

build('job1')

build('job2') }

} }

} O/P

TRIGGER BUILDS

22 Jenkins Pipeline by

Trigger second job even first job fails

if we triggering two job, if first job got failed, it wont trigger the second job.so we gng say propagate:false, so even though job failed, second job will get trigger.

pipeline { agent any

stages { stage('triggerjob') {

steps {

build(job:'job1', propagate:false)

build('job2') }

} }

}
even though job1 failed, its showing succes status.

change build result

while using the below function, it will store the status in jobresult, now eventhough job failed, it will run triffer both job, but it will show unstable result status

jobresult = build(job:'jobname', propagate:false).result

syntax

pipeline {

agent any

stages {

stage('triggerjob') {

steps {

script{

jobresult = build(job:'job1', propagate:false).result

build('job2')

if(jobresult=='FAILURE'){

currentBuild.result='UNSTABLE'

} }

}

23 Jenkins Pipeline by

} }

} O/P

Trigger other job with parameters

Already job is created, it contains parameter data to build job

Running job pipeline script

pipeline {

agent any

parameters {

choice(

name: 'Nodes',

choices:"Linux\nMac",

description: "Choose Node!")

choice(

name: 'Versions',

choices:"3.4\n4.4",

description: "Build for which version?" )

string(

name: 'Path',

defaultValue:"/home/pencillr/builds/",

description: "Where to put the build!")

}

stages {

} }

}

stage("build") {

steps {

script {

echo "$Nodes"

}

echo "Versions"

echo "Path"

}

24 Jenkins Pipeline by

triggering job pipeline script:

pipeline {

agent any

stages {

stage("build") {

steps {

script {

build(job: "builder-job",

parameters:

}

[string(name: 'Nodes', value: "Linux"),

string(name: 'Versions', value: "3.4"),

string(name: 'Path', value: "/home/pencillr/builds/}")])

}

} }

}

Schedule Jobs

Cron - trigger job will run depends up the cron schedule

} }

pipeline {

agent any

options{

timestamps()

triggers{

stages {

cron('* * * * *')

stage("cron") {

steps {

25 Jenkins Pipeline by Kalaiarasan

} }

echo "heloo"

}

}

job is running every min

Poll SCM-

will trigger the job depends up the changes in code, if there is no commit it wont run.

pipeline {

agent any

} }

} }

}

options{

timestamps()

triggers{

pollSCM('* * * * *')

stages {

stage("cron") {

steps {

echo "heloo"

git url:"https://github.com/kalaiarasan33/public.git"

}

26 Jenkins Pipeline by Kalaiarasan

Parallel

Multiple steps sections under same stage

No we cant use multiple steps in same stage.like below

stages {

stage("cron") {

steps {

echo "step1"

}

steps {

echo "step2"

}

}

}

Parallel builds -- it will trigger the build parallely pipeline {

27 Jenkins Pipeline by Kalaiarasan

agent any

stages {

stage("build") {

parallel{

stage('job1'){

steps{

echo "job1"

}

stage('job2'){

steps{

echo "job2"

}

} }

}

}

build Job is triggering parallely

Parallel stages:

pipeline {

}

}

agent any

options{

}

timestamps()

stages {

stage("stage1") {

parallel{

stage('stage1job1'){

}

steps{

echo "stage1job1"

sleep(10)

}

stage('stage1job2'){

28 Jenkins Pipeline by Kalaiarasan

} }

}

failFast

}

steps{

echo "stage1job2"

sleep(10)

}

}

}

stage("stage2") {

parallel{

stage('stage2job1'){

steps{

echo "stage2job1"

sleep(5)

}

stage('stage2job2'){

steps{

echo "stage2job2"

sleep(5)

}

}

}

}

O/P of parallel build

In parallel, eventhough any job is failed, it wont stop, it will execute other job. If we want any job is failed, it

should stop the other build means we need to use failFast

29 Jenkins Pipeline by Kalaiarasan

pipeline {

agent any

options{

}

timestamps()

stages {

stage("stage1") {

failFast true

parallel{

stage('stage1job1'){

steps{

echo "stage1job1"

sleep(10)

}

stage('stage1job2'){

sleep(10)

steps{

eecho "stage1job2"

}

stage('stage2job1'){

steps{

echo "stage2job1"

sleep(5)

}

sleep(5)

stage('stage2job2'){

steps{

echo "stage2job2"

}

}

}

} }

}

}

}

}

POST JOBS

post will execute after the completion of pipeline's stages section contains the following blocks

30 Jenkins Pipeline by Abid Moon

Post stage and stages level

Fixed: current status is success and previous status is failed

Always

: Runs always, wont depend upon the build result

changed

: Runs only if current build status is changed when compare to previous

Regression

: if current status is fail/unstable/aborted and previous run is successful.

Aborted

: if the current status is aborted

Failure

: Runs only if the current build status is failed.

Success

: current build is success

Unstable

: current build is unstable

cleanup

: like always, will execute at every time in the last ( if you want to delete any workspace and cleaup

any folder , we can use this)

31 Jenkins Pipeline by Abid Moon

pipeline {

agent any

options{

}

timestamps()

stages {

stage("stage1") {

post{

steps{

sh "ls -l"

always{

echo " action always "

changed{

regression{

echo " action always Changed from previous state"

echo " action Fixed when previous state is failure"

echo " action when current state is fail/unstable/aborted , previous state is

success"

}

} fixed{

}

} } } } }

}

} }

} }

}

aborted{

echo " action always aborted"

failure{

echo " action always failure"

success{

echo " action always success"

unstable{

echo " action unstable"

cleanup{

echo " action similar like always , it is using to cleanup folder or

workspace"

32 Jenkins Pipeline by Abid Moon

Previous build is failed, current build success O/P.

Previous build is success O/P

So always only executed, there no action for change and fixed

So Always , change (changes in state from previous state ), fixed (previous buil failed, current passed), all

executed

33 Jenkins Pipeline by Kalaiarasan

34 Jenkins Pipeline by Kalaiarasan

TOOLS

If you want to run specific version of tools to use in pipeline for specific job, so we using tools. Ex: maven in two version

pipeline{

agent any

tools{

}

} }

}

maven 'Maven3.6.1'

stages{

stage('tools_version'){

steps{

sh 'mvn --version'

}

35 Jenkins Pipeline by Abid Moon

O/P

Different version maven in job

}

} }

}

pipeline{

agent any

tools{

maven 'Maven3.5.0'

stages{

stage('tools_version'){

steps{

sh 'mvn --version'

}

36 Jenkins Pipeline by Abid Moon

Tools in Stage level :

}

}

} }

}

}

pipeline{

agent any

tools{

maven 'Maven3.6.1'

stages{

stage('tools_version'){

steps{

}

sh 'mvn --version'

stage('diff_version_stage_level'){

tools{

maven 'Maven3.5.0'

steps{

echo "stage level"

sh 'mvn --version'

}

37 Jenkins Pipeline byAbid Moon

Conditional and Loop Statements

IF Condition:
We can use Groovy coding functionalities using script {...} section.

pipeline{

agent any

environment{

Tools='Jenkins'

stages{

stage('conditions'){

steps{

script{

if(Tools == 'Jenkins'){

echo 'Tools is jenkins'

echo 'Tools is not jenkins '

}

}else{ }

38 Jenkins Pipeline by Abid Moon

}

} }

}

}

Demo : check build number even or Odd

pipeline{

agent any

environment{

stages{

Tools='Jenkins'

stage('conditions'){

steps{

script{

int buildno="$BUILD_NUMBER"

if(buildno %2 == 0){

echo 'builno is even'

echo 'buildno is odd'

}

}

} }

}

}else{

} }

39 Jenkins Pipeline by Kalaiarasan

Demo: For loop

pipeline{

agent any

environment{

script{

Tools='Jenkins'

stages{

stage('conditions'){

steps{

for(i=0;i<=5;i++){

}

println i

int buildno="$BUILD_NUMBER"

if(buildno %2 == 0){

echo 'builno is even'

echo 'buildno is odd'

}

}

} }

}

} }

}else{

Other Example

40 Jenkins Pipeline by Abid Moon

Ansicolor:

we need to install the plugin first , then set the ansi in configuration , jenkins foreground

pipeline{

agent any

stages{

}

} }

}

stage('ansi'){

steps{

ansiColor('xterm') {

echo 'something that outputs ansi colored stuff'

}

}

steps{

stage('non_ansi'){

echo 'non_ansi'

}

41 Jenkins Pipeline by Kalaiarasan

Change Build Number to Name

This is used to define the name for the job and description.

pipeline{

agent any

stages{

} }

} O/P

stage('buid_name'){

steps{

script{

currentBuild.displayName = "Deployment"

currentBuild.description = "This is deployment build"

}

echo 'build name changing'

}

42 Jenkins Pipeline by Kalaiarasan

dir, cleanws

create folder inside workspace -> job name -> (creating folder) -> job output is here

kalai@jenlinux:~/jenkins_home/workspace/Example$ cd delete_WS/ --> job name kalai@jenlinux:~/jenkins_home/workspace/Example/delete_WS$ ls

build_one build_one@tmp -> folder we created with dir function kalai@jenlinux:~/jenkins_home/workspace/Example/delete_WS$ cd build_one kalai@jenlinux:~/jenkins_home/workspace/Example/delete_WS/build_one$ ls hello.txt --> output created kalai@jenlinux:~/jenkins_home/workspace/Example/delete_WS/build_one$ pwd /home/kalai/jenkins_home/workspace/Example/delete_WS/build_one

Creating output in workspace -> jobname -> build_one --> outputfiles

dir('build_one'){

}

Creating output in workspace -> jobname -> build_one --> outputfiles --> deleted job workspace

kalai@jenlinux:~/jenkins_home/workspace/Example/delete_WS/build_one/..$ cd ..
kalai@jenlinux:~/jenkins_home/workspace/Example$ ls
change_build_name  change_build_name@tmp
kalai@jenlinux:~/jenkins_home/workspace/Example$

pipeline{

agent any

stages{

stage('cleanWS'){

steps{

script{

currentBuild.displayName = "Deployment"

currentBuild.description = "This is deployment build"

sh "echo dir creation and delete WS > hello.txt"

}

} }

}

}

pipeline{

agent any

stages{

stage('cleanWS'){

steps{

script{

dir('build_one'){

currentBuild.displayName = "Deployment"

sh "echo build name changing > hello.txt"

currentBuild.description = "This is deployment build"

}

}

cleanWs()

43 Jenkins Pipeline by Kalaiarasan

} }

}

stage('write_file'){

}

Write file_Jenkins syntax

Creating file in jenkins syntax

pipeline{

agent any

stages{

} }

}

steps{

}

writeFile file: 'newfile.txt' , text:"my file content is very small"

archiveArtifacts '*.txt'

44 Jenkins Pipeline by Kalaiarasan

tools{

Sample Maven Build

Build the maven project

}

} }

}

pipeline{

agent any

maven 'Maven3.6.1'

stages{

stage('maven_project'){

steps{

git url:"https://github.com/nkarthikraju/MavenExamples.git"

sh "mvn clean install"

}

without moving into the directory , it will show error , no pom file

45 Jenkins Pipeline by Kalaiarasan

now moved to directory wth help of dir function then executing maven clean install

pipeline{

agent any

tools{

}

} }

}

maven 'Maven3.6.1'

stages{

stage('maven_project'){

steps{

}

git url:"https://github.com/nkarthikraju/MavenExamples.git"

dir('MavenHelloWorldProject'){

}

sh "mvn clean install"

}

Archive artifacts and finger prints

getting archiveArtifacts when build is success

pipeline{

agent any

tools{

maven 'Maven3.6.1'

stages{

stage('maven_project'){

steps{

46 Jenkins Pipeline by Kalaiarasan

git url:"https://github.com/nkarthikraju/MavenExamples.git"

dir('MavenHelloWorldProject'){

sh "mvn clean install"

}

post{

success{

archiveArtifacts "MavenHelloWorldProject/target/*.jar"

} }

}

Fingerprint:

}

}

} }

if we execute the same job 10 times or etc, it will give same name output , for the identificaton or record the

artifacts with fingerprint it will create checksum with build.

pipeline{

agent any

tools{

maven 'Maven3.6.1'

stages{

stage('maven_project'){

steps{

git url:"https://github.com/nkarthikraju/MavenExamples.git"

dir('MavenHelloWorldProject'){

post{

sh "mvn clean install"

}

success{

archiveArtifacts artifacts:"MavenHelloWorldProject/target/*.jar" , fingerprint:true

} }

} O/P

}

} }

47 Jenkins Pipeline by Abid Moon

Uses of Credentials Option

if we pass the password it will transparent

}

} }

}

pipeline{

agent any

environment{

pass="jobs123"

stages{

stage('passwd'){

steps{

echo "password $pass"

}

48 Jenkins Pipeline 

another option passing the password as parameter with (password parameter)

} }

} }

}

O/P

pipeline{

agent any

environment{

pass="jobs123"

parameters{

password(name:'entry_password')

stages{

stage('passwd'){

steps{

echo "password $pass, password parameter $entry_password"

}

49 Jenkins Pipeline by Kalaiarasan

Now password with credential function create sceret text in credentials in jenkins

pipeline{

agent any

environment{

pass="jobs123"

passwod=credentials('DB_PASSWORD')

} }

"

} }

}

parameters{

password(name:'entry_password')

stages{

$passwod

stage('passwd'){

steps{

echo "password $pass, parameter password $entry_password , credential funtion password

}

CheckOS_AndExecuteSteps

if we execute like below it will show error, so we need to check the os type with of function

50 Jenkins Pipeline 

pipeline{

agent any

stages{

} }

}

stage('os_type'){

steps{

sh "ls"

bat "dir"

}

now it will check the ostype and then it will execute

pipeline{

agent any

stages{

stage('os_type'){

steps{

script{

if(isUnix()){

sh "ls"

}else{

bat "dir"

}

}

}

} }

}

This is linux machine, so linux command executed

51 Jenkins Pipeline 

pipeline{

agent any

environment{

stages{

} }

}

tools='jenkins'

}

stage('trimming_string'){

Trim

steps{

script{

t1=tools[0..6] //jenkins

}

t2=tools[3..5] //kin

echo "$t1 , $t2"

}

InPut Section

Install the plugin

52 Jenkins Pipeline 

pipeline {

agent any

stages {

stage('build user') {

steps {

wrap([$class: 'BuildUser']) {

sh 'echo "${BUILD_USER}"'

} }

} }

}

it will pull the user name

Build in specific user

pipeline{

agent any

stages{

stage('user_input'){

steps{

wrap([$class: 'BuildUser']){

script{

def name1="${BUILD_USER}"

echo "${BUILD_USER}, $name1"

if(name1=='kalai'){

echo "only kalai can able to build"

}else{

echo "others cant able to build"

} }

}

} }

} }

53 Jenkins Pipeline 

User input procced or abort

script{

}

pipeline{

} }

user I/P procced or abort

} }

agent any

stages{

stage('user_input'){

steps{

input("please approve the build")

sh "echo this is kalai"

if proceed it will start

54 Jenkins Pipeline 

Read Input From Specific user:

we can give list of user permission to proceed, other cant give proceed and get specific string from submitter.

pipeline{

agent any

stages{

stage('user_input'){

input{

message "press ok to continue"

submitter "kalai,lead"

parameters{

string(name:'username1',description: "only kalai and lead has permission")

steps{

echo "User : ${username1} said ok"

} }

} }

can pass the string:

} }

55 Jenkins Pipeline 

here is said manager

We can check out the jenkinsfile in scm whether it is git or SVN.and can maintain with version control.

SCM GIT

56 Jenkins Pipeline by Kalaiarasan

GIT checkout with the help of Pipeline syntax option

We can genereate the pipiline code from pipeline syntax option

We can generate the pipeline syntax from passing the parameter to plugin , then with generate option

57 Jenkins Pipeline by 

Commit Code

This script will read the file and write and push to the git

pipeline{
agent any

stages{

stage('commitcode'){

dir('comit_from_jenkins'){

git 'https://github.com/kalaiarasan33/jenkins_commit.git'

oldv=readFile('file.txt')

newv=oldv.tpInteger() + 1

writeFile file:"file.txt", text:"$newv"

git add file.txt

git commit -m "files commited"

} }

Create tag for every build.

pipeline{
agent any

stages{

} }

} }

stage('commitcode'){

steps{
cleanWs()

script{

}
sh """

""" }

git push

steps{

} }

sh sh sh

git 'https://github.com/kalaiarasan33/jenkins_commit.git'

dir('tag_jenkins'){

"git checkout master"

"git tag Deployement.$BUILD_NUMBER"

"git push origin Deployement.$BUILD_NUMBER"

58 Jenkins Pipeline by Kalaiarasan

}

Save Build Numbers which are used for Deployment in the file

pipeline{
agent any

stages{

} }

}
O/P
Buid no will add in the deployment file

stage('builnum'){

steps{

} }

git 'https://github.com/moonabid/jenkins_commit.git'

sh "echo $BUILD_NUMBER >> Deployment.txt"

dir('save_builnum_jenkins'){

sh """

git push """

git add file.txt

git commit -m "updating with build num commited"

59 Jenkins Pipeline by Kalaiarasan

jenkins file in brancher folder

SVN examples

Stages based on When condition

pipeline{
agent any

stages{
when{

}
steps{

stage('svn'){

changelog 'build'

sh """

60 Jenkins Pipeline by Kalaiarasan

}

} }

} }

"""

echo "found build keyword in the commit, so proceeding futher satge "

If you commit with build message, then it will build

WHEN

When is similar to If condition, but its more adavanced with in-built condition

61 Jenkins Pipeline 

Equals and not Equals:

pipeline{
agent any

} stages{

environment{

stage('When_equals'){

equals expected:'Docker' , actual: "$Tool"

echo " if when equal "

stage('When_no_equals'){

environment name:Tool , value:"Jenkins"

echo " if when not equal "

} }

T

ool="Jenkins"

when{

}
steps{

} }

when{
not {

}

} }

sh """

"""

}
steps{

O/P equal expected is not matched , not equals is matched

sh """

"""

62 Jenkins Pipeline by Kalaiarasan

O/P equal expected is matched , not equals is matched.

pipeline{
agent any

} stages{

environment{

stage('When_equals'){

equals expected:'Jenkins' , actual: "$Tool"

echo " if when equal "

stage('When_no_equals'){

environment name:Tool , value:"Jenkins"

echo " if when not equal "

} }

T

ool="Jenkins"

when{

}
steps{

} }

when{
not {

}

} }

sh """

"""

}
steps{

sh """

"""

63 Jenkins Pipeline by Kalaiarasan

Check previous build result and execute steps

execute whe n previous build is success

pipeline{
agent any

} stages{

environment{

} }

T

ool="Jenkins"

stage('hello_world'){

stage('based_on_previous'){

}
steps{

steps{

} }

when{

}

} }

sh """

"""

expression {

currentBuild.getPreviousBuild().result =='SUCCESS'

sh """

"""

echo " hello_world "

echo " previous build is failled, now sucess"

64 Jenkins Pipeline by Kalaiarasan

When previous build is failure

pipeline{
agent any

} stages{

environment{

} }

T

ool="Jenkins"

stage('hello_world'){

stage('based_on_previous'){

}
steps{

steps{

} }

when{

}

} }

sh """

"""

expression {

currentBuild.getPreviousBuild().result =='FAILURE'

sh """

"""

echo " hello_world "

echo " previous build is failled, now sucess"

65 Jenkins Pipeline

Steps based on commit messages (jenkinsfile : SCM)

when they commited with message build, it will get execute

pipeline{
agent any

stage('svn'){

changelog 'build'

echo "found build keyword in the commit, so proceeding futher satge "

stages{
when{

}
steps{

} }

} }

Steps based on Committed files (jenkinsfile : SCM)

sh """

"""

}

pipeline{
agent any

stages{
when{

}

changeset '*.py' steps{

} }

stage('pythonfile'){

sh """

"""

echo "commit files contains only for python file "

66 Jenkins Pipeline by Kalaiarasan

stage('java_file'){

echo " commit files contains only for xml file"

}

} }

environment{

Tool="jenkins"

envv="PRD"

stage('allof'){

when{ allOf{

when{

} steps{

} }

sh """

"""

changeset '*.xml'

Allof, Anyof

pipeline{
agent any

} stages{

} }

equals expected: "jenkins" , actual: "$Tool"

equals expected: "PRD" , actual: "$envv"

steps{

} }

sh """

"""

echo " when both condition is pass "

67 Jenkins Pipeline by Kalaiarasan

stage('anyof'){

} }

} }

when{ anyOf{

}
} steps{

} }

sh """ """

equals expected: "jenkins" , actual: "$Tool"

equals expected: "STG" , actual: "$env"

echo " when any one condition is pass"

Execute stage if required string is matched in the file

pipeline{
agent any

stages{
when{

stage('string_in_file'){

}

} }

steps{

expression{ return readFile('C:\\Users\\user\\Desktop\\cloudguru_sysops\\files.txt').contains('truncated')}

sh """ """

echo " string in file "

Skip Stage always

if you want to skip the stage or skip for few days.

68 Jenkins Pipeline by Kalaiarasan

pipeline{
agent any

stages{
when{

} }

Shell Syntax and Commands

pipeline{
agent any

stages{

SHELL

stage('string_in_file'){

}

return false

} }

steps{

expression{ return readFile("C:\\Users\\user\\Desktop\\cloudguru_sysops\\files.txt").contains('truncated')}

sh """ """

echo " string in file "

} }

stage('shell'){

steps{

} }

ls -l pwd

sh """

"""

Create file with Build Number and Build Name

pipeline{

69 Jenkins Pipeline by Kalaiarasan

} }

pipeline{
agent any

stages{

} }

agent any stages{

stage('shell'){

steps{

} }

sh """

"""

ls -l pwd

stage('html'){

touch ${JOB_NAME}.${BUILD_NUMBER}.txt

steps{
bat """

""" }

}

steps{
bat """

""" }

} }

Sample Local Deployment

Create Html and Copy to the location.

echo hello this is my HTML >> "D:\\"

stage('copy_location'){

copy *.html D:\\tomcat\\


No comments:

Post a Comment

Jenkins Pipeline

  Jenkins Pipeline Pipeline As Code About Me Lots of Engineers aspire to be full-stack, but I don't. I aspire to be a T-Shaped Engineer....