Configuring CI Using Jenkins and Nx
Below is an example of a Jenkins setup, building and testing only what is affected.
1pipeline {
2 agent none
3 environment {
4 NX_BRANCH = env.BRANCH_NAME.replace('PR-', '')
5 }
6 stages {
7 stage('Pipeline') {
8 parallel {
9 stage('Main') {
10 when {
11 branch 'main'
12 }
13 agent any
14 steps {
15 // This line enables distribution
16 // The "--stop-agents-after" is optional, but allows idle agents to shut down once the "e2e-ci" targets have been requested
17 // sh "npx nx-cloud start-ci-run --distribute-on='3 linux-medium-js' --stop-agents-after='e2e-ci'"
18 sh "npm ci"
19
20 // Prepend any command with "nx-cloud record --" to record its logs to Nx Cloud
21 // This requires connecting your workspace to Nx Cloud. Run "nx connect" to get started w/ Nx Cloud
22 // sh "npx nx-cloud record -- nx format:check"
23
24 // Without Nx Cloud, run format:check directly
25 sh "npx nx format:check"
26 sh "npx nx affected --base=HEAD~1 -t lint test build e2e-ci"
27 }
28 }
29 stage('PR') {
30 when {
31 not { branch 'main' }
32 }
33 agent any
34 steps {
35 // This line enables distribution
36 // The "--stop-agents-after" is optional, but allows idle agents to shut down once the "e2e-ci" targets have been requested
37 // sh "npx nx-cloud start-ci-run --distribute-on='3 linux-medium-js' --stop-agents-after='e2e-ci'"
38 sh "npm ci"
39
40 // Prepend any command with "nx-cloud record --" to record its logs to Nx Cloud
41 // This requires connecting your workspace to Nx Cloud. Run "nx connect" to get started w/ Nx Cloud
42 // sh "npx nx-cloud record -- nx format:check"
43
44 // Without Nx Cloud, run format:check directly
45 sh "npx nx format:check"
46 sh "npx nx affected --base origin/${env.CHANGE_TARGET} -t lint test build e2e-ci"
47 }
48 }
49 }
50 }
51 }
52}
53Get the Commit of the Last Successful Build
Unlike GitHub Actions and CircleCI, you don't have the metadata to help you track the last successful run on main. In the example below, the base is set to HEAD~1 (for push) or branching point (for pull requests), but a more robust solution would be to tag an SHA in the main job once it succeeds and then use this tag as a base. See the nx-tag-successful-ci-run and nx-set-shas (version 1 implements tagging mechanism) repositories for more information.
We also have to set NX_BRANCH explicitly.