Skip to content

Advanced

Andrew Bayer edited this page Jan 10, 2017 · 6 revisions

The pipeline you have seen so far has been mostly declarative. You can do a lot more with pipeline (in fact there isn't really anything you can't do, if you are careful).

Using pipeline scripting inside stages

If you need to use lower-level pipeline script inside stages, you can use script - this is a powerful tool not to be used lightly. The script block allows you to use the full power of pipeline.

pipeline {
      agent any
      stages {
        stage('build') {
          steps {
             sh 'echo hello world'
             script {
              def thing = someLibrary.someMethod("hi");
              .. do something with thing.. 
              .. with great power comes great responsibility ...
             }
          }
        }
      }

}

Wrapping steps around pipelines

You can use block-scoped steps like retry or timeout in a stage, but you can also use those steps across the whole build using the options section.

pipeline {
    agent any
    
    options {
       retry(3)
       timeout time:5, units:'MINUTES'
    }
    
    stages {
        stage('build') {
            sh 'run-build.sh'
        }
    }
}

Controlling when stages execute

Using the when construct, you can specify a true/false condition. Depending on the outcome of this condition, the stage will be "skipped".

The most common usage of this would be to chose what branch to run a stage on:

   stage('production') {
        when {
            branch "master"
        }
        steps ...
   }

You can use many other environment variables to programmatically decide if a stage should run.

Breaking out of declarative pipeline

Any script you put outside of the pipeline construct will be the same as if it were in a script block. This is non-declarative Groovy CPS DSL that pipeline uses under the covers. If those words sound scary, you probably don't want to do this. With great power comes great responsibility. There are a lot fewer restrictions and validations when you use script outside of pipeline. There is also more verbosity to do common things...

Finding what steps are available

To see what steps are available, if you go to the page for a pipeline in Jenkins, on the left there will be a link that says "Pipeline Syntax" - click on that and you get a syntax builder that can enumerate what other steps (other than sh) are available on your Jenkins instance (normally installed via plugins).

Read more

TODO: where should this link to?