Custom Distributed Task Execution on Jenkins
Using Nx Agents is the easiest way to distribute task execution, but it your organization may not be able to use hosted Nx Agents. With an enterprise license, you can set up distributed task execution on your own CI provider using the recipe below.
Distribute Tasks Across Custom Agents on Jenkins
Run agents directly on Jenkins with the workflow below:
1pipeline {
2 agent none
3 environment {
4 NX_BRANCH = env.BRANCH_NAME.replace('PR-', '')
5 NX_CLOUD_DISTRIBUTED_EXECUTION_AGENT_COUNT = 3
6 }
7 stages {
8 stage('Pipeline') {
9 parallel {
10 stage('Main') {
11 when {
12 branch 'main'
13 }
14 agent any
15 steps {
16 sh "npm ci"
17 sh "npx nx-cloud start-ci-run --stop-agents-after='e2e-ci'"
18 sh "npx nx-cloud record -- nx format:check"
19 sh "npx nx affected --base=HEAD~1 -t lint,test,build,e2e-ci --configuration=ci --parallel=2"
20 }
21 }
22 stage('PR') {
23 when {
24 not { branch 'main' }
25 }
26 agent any
27 steps {
28 sh "npm ci"
29 sh "npx nx-cloud start-ci-run --stop-agents-after='e2e-ci'"
30 sh "npx nx-cloud record -- nx format:check"
31 sh "npx nx affected --base origin/${env.CHANGE_TARGET} -t lint,test,build,e2e-ci --parallel=2 --configuration=ci"
32 }
33 }
34
35 # Add as many agent you want
36 stage('Agent1') {
37 agent any
38 steps {
39 sh "npm ci"
40 sh "npx nx-cloud start-agent"
41 }
42 }
43 stage('Agent2') {
44 agent any
45 steps {
46 sh "npm ci"
47 sh "npx nx-cloud start-agent"
48 }
49 }
50 stage('Agent3') {
51 agent any
52 steps {
53 sh "npm ci"
54 sh "npx nx-cloud start-agent"
55 }
56 }
57 }
58 }
59 }
60}
61
This configuration is setting up two types of jobs - a main job and three agent jobs.
The main job tells Nx Cloud to use DTE and then runs normal Nx commands as if this were a single pipeline set up. Once the commands are done, it notifies Nx Cloud to stop the agent jobs.
The agent jobs set up the repo and then wait for Nx Cloud to assign them tasks.
Two Types of ParallelizationThe agents and the --parallel
flag both parallelize tasks, but in different ways. The way this workflow is written, there will be 3 agents running tasks and each agent will try to run 2 tasks at once. If a particular CI run only has 2 tasks, only one agent will be used.