18

I'm trying to convert few Jenkinsfiles from Scripted Pipeline to Declarative Pipeline. I have a block like this in a Jenkinsfile:

ws("/path/to/dir") {
    // do stuff
}

I wonder what does it do exactly and what's the proper way to convert it to the Declarative Pipeline syntax.

Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378

1 Answers1

24

ws allocates a new workspace. you would use this to ensure that nothing else interferes with the location on disk where you are running the enclosed steps.

  • this is not as heavy-handed as the node step, since node will also ensure that it gets run with a separate executor.
  • this provides more isolation than the dir step, since dir will not ensure an isolated location on the filesystem the way ws will.

you can use it in a declarative pipeline in the same way as scripted:

pipeline {
  agent { label 'docker' }
  stages {
    stage('hot_stage') {
      steps {
        sh 'pwd'
        ws('/tmp/hey') {
          sh 'pwd'
        }
      }
    }
  }
}

produces output:

+ pwd
/opt/jenkins/workspace/tool_jenkins2-test_master-R4LIKJR63O6POQ3PHZRAKWWWGZZEQIVXVDTM2ZWZEBAWE3XKO6CQ
[Pipeline] ws
Running in /tmp/hey
[Pipeline] {
[Pipeline] sh
[hey] Running shell script
+ pwd
/tmp/hey

references:

burnettk
  • 13,557
  • 4
  • 51
  • 52
  • Thanks for the anwer. With a declarative pipeline I get an exception though: `java.io.IOException: Failed to mkdirs: /path/to/dir`. Any idea why it can occur ? – Eugene Yarmash Apr 24 '17 at 00:12
  • lack of permissions will cause that. could that be happening? maybe you're on a different slave than you were on with the scripted pipeline? i just now tested a path where multiple levels of directories needed to be created, and that worked just great for me. can you post the Jenkinsfile? – burnettk Apr 24 '17 at 00:17
  • Weird. With declarative pipeline the shell commands get executed under a different user, which seems to cause the permissions issue.. – Eugene Yarmash Apr 24 '17 at 00:33
  • 1
    Note: with `ws()`, relative paths are relative to the "slave root". – cowlinator Oct 09 '20 at 23:42