The Workspace

The workspace is the directory on an agent where Jenkins checks out code and runs your build.

Every job gets a workspace — a folder on the agent where Jenkins checks out your source code and runs the build steps. All your commands execute with the workspace as the working directory.

What lives in the workspace

  • The checked-out source code.
  • Any files your build creates (compiled binaries, reports, logs).
  • Downloaded dependencies, unless cached elsewhere.

Workspace cleanup

By default Jenkins reuses the workspace between builds, which speeds things up but can leave stale files behind. For a truly clean build, wipe it first. The cleanWs() step (from the Workspace Cleanup plugin) does this in pipelines.

Example

Example · bash
# In a pipeline you can print and clean the workspace:

# steps {
#   sh 'pwd'          // prints the workspace path
#   sh 'ls -la'       // lists files in the workspace
# }
#
# post {
#   always {
#     cleanWs()       // wipe the workspace after the build
#   }
# }

When to use it

  • A build script references WORKSPACE to find generated files and copy them to an artifact directory.
  • A team wipes the workspace before each build to prevent stale files from causing inconsistent test results.
  • A pipeline uses the workspace path to pass the checkout directory to a Docker volume mount at build time.

More examples

Reference workspace in a build step

Uses the WORKSPACE environment variable to navigate and copy build outputs inside a shell step.

Example · bash
#!/bin/bash
# Jenkins sets WORKSPACE automatically
echo "Building in: $WORKSPACE"
cd "$WORKSPACE"
npm install
npm run build
cp -r dist/ "$WORKSPACE/artifacts/"

Clean workspace before build

Uses the cleanWs() option to delete the workspace at the start of every pipeline run for a clean build.

Example · groovy
pipeline {
  agent any
  options {
    cleanWs()  // wipe workspace before each run
  }
  stages {
    stage('Build') {
      steps { sh 'mvn package' }
    }
  }
}

Delete workspace in post block

Cleans the workspace in the post block so the agent disk is freed regardless of the build result.

Example · groovy
pipeline {
  agent any
  stages {
    stage('Build') { steps { sh 'make all' } }
  }
  post {
    always {
      cleanWs()
      echo "Workspace cleaned after build #${BUILD_NUMBER}"
    }
  }
}

Discussion

  • Be the first to comment on this lesson.