Opscraft
Jenkinsfile · Lesson 3 of 10 · 3 min read

Agents and workspaces

Agent variants

agent any                                        // any available executor
agent none                                       // no global agent; each stage declares one
agent { label 'linux && docker' }                // label expression
agent { node { label 'linux'; customWorkspace '/data/ws/orders' } }
agent { docker { image 'node:20-alpine'; args '-v $HOME/.npm:/root/.npm'; label 'docker' } }
agent { dockerfile { filename 'ci/Dockerfile'; label 'docker' } }   // build an image from the repo, run inside it
agent { kubernetes { yamlFile 'ci/pod.yaml'; defaultContainer 'maven' } }

agent none + per-stage agents

Using agent none at the top and declaring agents per stage lets you:

Enlarge diagramBuildmaven podUI testsnode podApproveno agent: freeDeploysmall tools podEach agent has its own workspace: stash in Build, unstash later (small files only).
Figure 1. agent none at the top, then an agent per stage: each stage gets the right toolchain, and nothing is held while a human approves.
Swipe sideways to see all of it, or tap to open it full screen.
  • run different stages with different toolchains (Maven pod for build, a Node pod for UI tests, a small pod for deploy);
  • avoid holding an executor while waiting (e.g. during input approval);
  • run stages on different architectures or OSes.

Each stage with its own agent gets its own workspace (and its own checkout). To pass build outputs between them, stash / unstash or publish to a repository:

stage('Build')  { agent { label 'maven' } steps { sh 'mvn -B package'; stash name: 'jar', includes: 'target/*.jar' } }
stage('Docker') { agent { label 'docker' } steps { unstash 'jar'; sh 'docker build -t $IMAGE:$GIT_COMMIT .' } }

Stashes travel through the controller — keep them small (MBs, not GBs). For large artifacts, push to S3/Nexus.

Enlarge diagramstage('Build')maven pod: stashtarget/*.jarcontrollerholds the stashstage('Docker')docker agent: unstashstashunstash
Figure 2. stash and unstash move small files between stages that run on different agents. They travel through the controller, so keep them small.
Swipe sideways to see all of it, or tap to open it full screen.

With agent { docker {...} } inside a stage, reuseNode true runs the container on the same node and workspace as the top-level agent instead of allocating a new one.

Workspaces

  • Workspaces persist on static agents between builds — stale files cause "works on rerun" bugs. Clean with cleanWs() (Workspace Cleanup plugin) in post { cleanup }, or use ephemeral pod agents.
  • Concurrent builds of the same job on one agent get suffixed workspaces (job@2).
  • dir('subdir') { ... } changes directory for enclosed steps; ws('/path') { ... } allocates a specific workspace.