DevOps Classroom Series – 16/May/2020

Pipelines

Preview

Jenkinsfile

  • In classic free sytle job configuratins will be changed over time, but in JENKINS-HOME you would see => latestversion
  • To fix this JOBCONFIGHISTORY plugin
  • In Pipeline Scripts the Whole idea is pipeline-as-code, Jenkins used a language called as Groovy and Jenkins has Domain Specific Language DSL
  • Jenkins pipleline script has two approaches
    • Scripted Pipeline
      • Imperative Style where you define the logic and program flow in the script itsef
      • Advantages:
        1. few sections
        2. Capability to use procedural code
        3. Much like creating a program
        4. More flexibility in doing custom opertions
      • Disadvantage:
        1. More programming is required
        2. Proper Sytnax checking (It is limited to Groovy)
        3. Very much different from classic Jenkins
      • Sample
      node {
          stage('scm'){
              
          }
      
          stage('build'){
              sh 'mvn package'
          }
      }
      
    • Declarative Pipeline
      • Declarative Style and are arranged in clear sections that states the outcomes
      • Advantages:
        • More Structured
        • Generally we declare what is need
        • Can be generated Blue Ocean graphical interface
        • Better syntax checking
      • Disadvantage:
        • Less support for iterative logic (less like a program)
        • Still evolving
        • Structure is more rigid
        • Currently not well suited for Complex pipelines
      • Sample:
      pipeline {
          agent {label 'MASTER'}
          stages {
              stage('Source'){
                  steps {
                      git 'https://github.com/dummyrepos/spring-petclinic.git' 
                  }
              }
              stage('Package'){
                  steps {
                      sh 'mvn package'
                  }
              }
          }
      }
      

Setting up Blue Ocean

  • Install Plugin called as Blue Ocean Preview
  • After Plugin installation is completed and jenkins is restarted Preview Preview

Jenkins System Components

Preview

Just Enough Groovy For Jenkins

  • Setting up groovy on local machine

    • Navigate to here and download groovy, unzip and add to the path
    • Better way:
      • Windows => using chocolatey choco install groovy -y
      • Mac => Refer Here
  • Groovy is a Java Based Language

  • Datatypes:

    • Ideally not necessary to worry about datatypes use def
    • Sample Code to use def
    def myvariable = true
    println 'value is '+myvariable+ ' type is '+ myvariable.getClass()
    
    • Use Datatype Directly
    String language = 'Groovy'
    println "Welcome to world of ${language}"
    BigDecimal amount = 823894798342.23
    println "Amount is ${amount}"
    int attempts = 3
    
    println "Successfull after ${attempts} attempts"
    
  • Interpolation:

# with string concat (+)
def myvariable = true
println 'value is '+myvariable+ ' type is '+ myvariable.getClass()


def myvariable = true
println "value is ${myvariable} and type is ${myvariable.getClass()}"

def language = 'Groovy'
println "Welcome to the world of ${language}"

  • Conditionals:
    • Refer Here
    • Look into if-else and switch
    • Example:
    def x = 4
    
    if (x>=5) {
    println "working good"
    }
    else {
    println "need to improve"
    }
    
  • Looping:
    • along with traditional while, for lets look into other looping
    println "Iterating from 0 to 10"
    for (index in 0..10) {
    println index
    }
    def items = ['red', 'green', 'blue']
    for (item in items) {
    println item
    }
    
    3.times {
    println "attempt number ${it}"
    }
    
  • Functions:
// This is returning some value
def sendmessage(){
    return "how are you"
}
// This doesnt return any valu
void printmessage(message) {
    println "Message sent is ${message} "
}

def myMessage = sendmessage()
printmessage(myMessage)
  • Maps in Groovy:

    • Map is collection of name value pairs
    • Sample
    // empty
    def myMap = [:]
    // add name
    myMap['name'] = 'QualityThought'
    // add age
    myMap['age'] = 10
    
    println "Name is ${myMap['name']} and age is ${myMap['age']}"
    
  • Importing Packages:

    • Code will fail if the package are note imported
    def jsonSlurper = new JsonSlurper()
    def object = jsonSlurper.parseText('{ "name": "John Doe" } ')
    
    assert object instanceof Map
    assert object.name == 'John Doe'
    println "Name is ${object.name}"
    
    use ( TimeCategory ) {
            // application on numbers:
            println 1.minute.from.now
            println 10.days.ago
    
            // application on dates
            def someDate = new Date()
            println someDate - 3.months 
    }
    
    • Add the correct import statements
    import groovy.json.JsonSlurper
    import groovy.time.*
    
    def jsonSlurper = new JsonSlurper()
    def object = jsonSlurper.parseText('{ "name": "John Doe" } ')
    
    assert object instanceof Map
    assert object.name == 'John Doe'
    println "Name is ${object.name}"
    
    use ( TimeCategory ) {
            // application on numbers:
            println 1.minute.from.now
            println 10.days.ago
    
            // application on dates
            def someDate = new Date()
            println someDate - 3.months 
    }
    

Groovy In Jenkins

  • Jenkins already has script editor. Manage Jenkins => Script Console Preview
  • Execute the following in script editor
Jenkins.instance.pluginManager.plugins.each {
  plugin -> println " plugin is ${plugin} and the class name is ${plugin.getClass()} and url is ${plugin.getUrl()} "
}
  • Jenkins also provides Groovy plugin Preview
  • After Jenkins is Restarted, Navigate to build step of free style project Preview
  • Here we have two Groovy Scripts
    • Sytem Groovy: Runs in the Same JVM as Jenkins, so here we can control Jenkins
    • Groovy: This Groovy is execute on New Process (fork) where a JVM is differnt, so it will not have access to Jenkins

Scripted Pipeline Structure

  • Basic Structure is as shown below Preview
  • Basic Structure
node('<LABEL>') {
    stage('<stage name>') {
        <step>
        <step>
    }
}
  • Example:
node {
    stage('scm'){
        git 'https://github.com/dummyrepos/spring-petclinic.git'
    }

    stage('build'){
        sh 'mvn package'
    }
}

Declarative Pipeline Structure

  • Basic Structure: Preview
  • Syntax
pipeline {
    agent ''
    stages {
        stage('<name>') {
            steps {

            }
        }
    }
}
  • Example:
pipeline {
    agent {label 'MASTER'}
    stages {
        stage('Source'){
            steps {
                git 'https://github.com/dummyrepos/spring-petclinic.git' 
            }
        }
        stage('Package'){
            steps {
                sh 'mvn package'
            }
        }
    }
}

  • Refer Here for syntax

  • Now lets write a Jenkinsfile using a declarative pipeline

  • For git scm Refer Here

node('REDHAT') {
    stage('scm'){
        git branch: 'master', url: '=https://github.com/dummyrepos/game-of-life.git'
    }
}
  • In the declarative mode, Refer Syntaxes from [here](https://www. jenkins.io/doc/book/pipeline/syntax/)
pipeline {
    agent { label 'REDHAT' }
    triggers { pollSCM('* * * * *') }
    stages {
        stage('clone and compile') {
            steps {
                git branch: 'declarative', 
                url: 'https://github.com/dummyrepos/game-of-life.git'
                sh 'mvn compile'
            }
        }
    }
}

Multi branch pipeline

  • Creates a build for every branch in Git Repo
  • Ensure every branch has Jenkinsfile Preview

Leave a Reply

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

About learningthoughtsadmin