Code Snippet

Just another Code Snippet site

[Jenkins] Pipeline Script – How to

Start another job :

node {
    stage('Run 1st job') {
        sh 'date'
        build job: 'Job1'
    }
}

Parallel :

node {
    stage('Run all jobs //') {
        parallel (
            phase1: { build job: 'Job1'},
            phase2: { build job: 'Job2'},
            phase3: { build job: 'Job3'}
        )
    }
}

Check job result :

node {
    def result
    stage('Check Job result') {
        sh 'date'
        result = build job: 'Job1'
    }

    if(result.result == 'FAILURE') {
        echo '1. Set result to unstable'
        currentBuild.result = 'UNSTABLE'
    } else {
        echo '2. Set result to '+result.result.toString()
       currentBuild.result = result.result
     }
}


9 thoughts on “[Jenkins] Pipeline Script – How to

  • Olivier says:

    Define a complex object :

        def slackNotifications = [:]
        
        slackNotifications["APP1"] = [key1:"APP1_val1", key2:"APP1_val2", key3:["A", "B", "C"]]
        slackNotifications["APP2"] = [key1:"APP2_val1", key2:"APP2_val2"]
        
        echo slackNotifications["APP1"].key1
        echo slackNotifications["APP2"].key2
        echo slackNotifications["APP1"].key3[1]
    
  • Olivier says:

    Pipeline & Maven tool

    def mvn_version = 'M3'
    withEnv( ["PATH+MAVEN=${tool mvn_version}/bin"] ) {
      //sh "mvn clean package"
    }
    
    • Olivier says:
      pipeline {
          
          agent {
              node {
                  label 'jdk7'
              }
          }
          
          tools {
              jdk 'jdk1.7'
              maven 'maven-3.3.9'
          }
          
          environment {
              MAVEN_OPTS = ' -Xmx1024m -XX:MaxPermSize=256m'
          }
          
          stages{
              stage('Build') {
                  steps {
                      sh "mvn --version"
                      sh "mvn clean install"
                  }
              }
          }
      }
      
  • Olivier says:

    Declarative pipeline sample :

    #!/bin/groovy
    pipeline {
        
        agent {
            node {
                label 'jdk7'
            }
        }
        
        options {
            disableConcurrentBuilds()
            timestamps()
            timeout(time: 1, unit: 'HOURS')
            buildDiscarder(logRotator(daysToKeepStr: '15', numToKeepStr: '5'))
        }
        
        triggers {
            pollSCM('@hourly')
        }
        
        tools {
            jdk 'jdk1.7'
            maven 'maven-3.3.9'
        }
        
        environment {
            MAVEN_OPTS = ' -Xmx1024m -XX:MaxPermSize=256m'
        }
        
        stages{
            stage('Build') {
                steps {
                    script {
                        def artifactory_server= Artifactory.server('artifactory_server')
                        
                        // Create and set an Artifactory Maven Build instance:
                        def rtMaven = Artifactory.newMavenBuild()
                        rtMaven.resolver server: artifactory_server, releaseRepo: 'custdev-libs-release-with-local', snapshotRepo: 'custdev-libs-snapshot'
                        rtMaven.deployer server: artifactory_server, releaseRepo: 'libs-release-local', snapshotRepo: 'libs-snapshot-local'
    
                        // Optionally include or exclude artifacts to be deployed to Artifactory:
                        // Set a Maven Tool defined in Jenkins "Manage":
                        //rtMaven.tool = 'maven-3.3.9'
    
                        // Optionally set Maven Ops
                        //rtMaven.opts = '-Xmx1024m -XX:MaxPermSize=256m'
    
                        // Run Maven:
                        def buildInfo = rtMaven.run pom: 'tooling/pom.xml', goals: 'clean install -B'
    
                        // Alternatively, you can pass an existing build-info instance to the run method:
                        // rtMaven.run pom: 'maven-example/pom.xml', goals: 'clean install', buildInfo: buildInfo
                         
                        // Publish the build-info to Artifactory:
                        artifactory_server.publishBuildInfo buildInfo
                    }
                }
            }
        }
    }
    
    
  • Olivier says:

    Upgrade Rancher (v1) Service

            stage('Deploy Rancher') {
                steps {
                    script {
                        rancher environmentId: "${RANCHER_ENV_ID}", endpoint: "${RANCHER_URL}", credentialId: 'rancher_api_key', service: "${RANCHER_SERVICE}", image: "${DOCKER_PUBLIC_REGISTRY}/${DOCKER_IMAGE_NAME}:${DOCKER_IMAGE_VERSION}", confirm: true
                    }
                }
            }
    
  • Keep maven color during pipeline :

    withMaven(mavenOpts: '-Djansi.force=true') {
        sh "mvn clean verify -Dstyle.color=always"
    }
    
    ...
        environment {
            MAVEN_OPTS = ' -Djansi.force=true '
        }
    ...
    sh 'mvn -Dstyle.color=always clean install'
    
  • Declare mutli upstream projects:

    upstream(upstreamProjects: "Folder/MyJob1,Folder/MyJob2", threshold: hudson.model.Result.SUCCESS)
    

    with multi branches:

    upstream(upstreamProjects: "Folder/MyJob1/" + env.BRANCH_NAME.replaceAll("/", "%2F")+",Folder/MyJob2/" + env.BRANCH_NAME.replaceAll("/", "%2F"), threshold: hudson.model.Result.SUCCESS)
    

    Doc: https://www.jenkins.io/doc/book/pipeline/syntax/#triggers

  • Jenkins Pipeline agent label from the parameter:

    pipeline {
        agent {
            label params.AGENT == "any" ? "" : params.AGENT 
        }
    
        parameters {
            choice(name: "AGENT", choices: ["any", "docker", "windows", "linux"]) 
        }
    
        stages {
            stage("Build") {
                steps {
                    echo "Hello, World!"
                }
            }
        }
    }
    
  • Docker agent:
    https://www.jenkins.io/doc/book/pipeline/docker/

    pipeline {
        agent {
            docker { image 'node:16.13.1-alpine' }
        }
        stages {
            stage('Test') {
                steps {
                    sh 'node --version'
                }
            }
        }
    }
    

    https://github.com/docker-library/official-images#consistency

Leave a Reply to Olivier Cancel reply

Your email address will not be published. Required fields are marked *