25

Jenkins declarative pipelines offer a post directive to execute code after the stages have finished. Is there a similar thing to run code before the stages are running, and most importantly, before the SCM checkout?

For example something along the lines of:

pre {
    always {
        rm -rf ./*
    }
}

This would then clean the workspace of my build before the source code is checked out.

FrontSide
  • 1,128
  • 2
  • 10
  • 12
  • I was looking for the same feature since we leverage a slack channel to post about our builds. It's a nice way to do "Build X started" – Ryan Gates Sep 12 '18 at 19:05

3 Answers3

27

pre is a cool feature idea, but doesn't exist yet. skipDefaultCheckout and checkout scm (which is the same as the default checkout) are the keys:

pipeline {
  agent { label 'docker' }
  options {
    skipDefaultCheckout true
  }
  stages {
    stage('clean_workspace_and_checkout_source') {
      steps {
        deleteDir()
        checkout scm
      }
    }
    stage('build') {
      steps {
        echo 'i build therefore i am'
      }
    }
  }
}
burnettk
  • 13,557
  • 4
  • 51
  • 52
  • 1
    I raises an error searching for my customized Dockerfile. – Antonio Petricca Apr 09 '18 at 14:10
  • dont understand how this is an answer to the question. can you run any code prior to say your parameters declaration or any pipeline stages using that options? – mike01010 May 26 '23 at 01:04
  • the OP was looking to do stuff, "most importantly, before the SCM checkout." this example shows how you can deleteDir() before SCM checkout. – burnettk May 26 '23 at 14:01
5

For the moment there are no pre-build steps but for the purpose you are looking for, it can be done in the pipeline job configurarion and also multibranch pipeline jobs, when you define where is your jenkinsfile, choose Additional Behaviours -> Wipe out repository & force clone.

Delete the contents of the workspace before building, ensuring a fully fresh workspace.

Additional Behaviours: Wipe out repository & force clone

If you do not really want to delete everything and save some network usage, you can just use this other option: Additional Behaviours -> Clean before checkout.

Clean up the workspace before every checkout by deleting all untracked files and directories, including those which are specified in .gitignore. It also resets all tracked files to their versioned state. This ensures that the workspace is in the same state as if you cloned and checked out in a brand-new empty directory, and ensures that your build is not affected by the files generated by the previous build.

This one will not delete the workspace but just reset the repository to the original state and pull new changes if there are some.

Additional Behaviours: Clean before checkout

froblesmartin
  • 1,527
  • 18
  • 25
1

I use "Prepare an environment for the run / Script Content"

script

Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
michal k
  • 11
  • 2