When you run your Jenkinsfile and it is obtained from a source repository, Jenkins automatically creates a workspace dynamically for the job and by default it places any other files in your project into that workspace.
In your example, you have used "agent any" then in your stage you are using Linux specific commands like "sh 'ls -l" to list the files. The first thing to be aware of is that "agent any" can run on any slave configured on your Jenkins server, hence it may run on a Linux or Windows slave depending upon the configuration. So the "sh" step may fail if that tries to run on a Windows slave. You can use agent with a label to be more specific on the node/slave selection like this (the labels available depend on your Jenkins slave config):
agent {
label "LINUX"
}
After building, it does not delete everything automatically as it keeps the workspace for each build of the job on the Jenkins master. You can solve this in 2 ways:
1) Use an options section in your pipeline to discard old builds:
options {
// Keep 4 builds maximum
buildDiscarder(logRotator(numToKeepStr: '4'))
}
2) Use a post-handler "always" section to clean up:
post {
always {
deleteDir()
}
}
Here is a pipeline that may help to get you started:
pipeline {
agent any
options {
buildDiscarder(logRotator(numToKeepStr: '4'))
}
stages {
stage('List files in repo on Unix Slave') {
when {
expression { isUnix() == true }
}
steps {
echo "Workspace location: ${env.WORKSPACE}"
sh 'ls -l'
}
}
stage('List files in repo on Windows Slave') {
when {
expression { isUnix() == false }
}
steps {
echo "Workspace location: ${env.WORKSPACE}"
bat 'dir'
}
}
}
post {
always {
deleteDir()
}
}
}
Here is the output I get with some of the Git chatter redacted:
Pipeline] node
Running on master in /var/jenkins_home/jobs/macg33zr/jobs/testRepo/branches/master/workspace
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Declarative: Checkout SCM)
Cloning the remote Git repository
Cloning with configured refspecs honoured and without tags
Cloning repository https://github.com/xxxxxxxxxx
[Pipeline] }
[Pipeline] // stage
[Pipeline] withEnv
[Pipeline] {
[Pipeline] stage
[Pipeline] { (List files in repo on Unix Slave)
[Pipeline] isUnix
[Pipeline] echo
Workspace location: /var/jenkins_home/jobs/macg33zr/jobs/testRepo/branches/master/workspace
[Pipeline] sh
[workspace] Running shell script
+ ls -l
total 8
-rw-r--r-- 1 jenkins jenkins 633 Oct 1 22:07 Jenkinsfile
-rw-r--r-- 1 jenkins jenkins 79 Oct 1 22:07 README.md
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (List files in repo on Windows Slave)
Stage 'List files in repo on Windows Slave' skipped due to when conditional
[Pipeline] isUnix
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Declarative: Post Actions)
[Pipeline] deleteDir
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline