Configuring CI Using GitLab and Nx
Below is an example of a GitLab pipeline setup for an Nx workspace - building and testing only what is affected.
1image: node:18
2
3stages:
4  - test
5  - build
6
7.distributed:
8  interruptible: true
9  only:
10    - main
11    - merge_requests
12  cache:
13    key:
14      files:
15        - package-lock.json
16    paths:
17      - .npm/
18  before_script:
19    - npm ci --cache .npm --prefer-offline
20    - NX_HEAD=$CI_COMMIT_SHA
21    - NX_BASE=${CI_MERGE_REQUEST_DIFF_BASE_SHA:-$CI_COMMIT_BEFORE_SHA}
22
23variables:
24  GIT_DEPTH: 0
25
26format-check:
27  stage: test
28  extends: .distributed
29  script:
30    - npx nx format:check --base=$NX_BASE --head=$NX_HEAD
31
32lint:
33  stage: test
34  extends: .distributed
35  script:
36    - npx nx affected --base=$NX_BASE --head=$NX_HEAD -t lint --parallel=3
37
38test:
39  stage: test
40  extends: .distributed
41  script:
42    - npx nx affected --base=$NX_BASE --head=$NX_HEAD -t test --parallel=3 --configuration=ci
43
44build:
45  stage: build
46  extends: .distributed
47  script:
48    - npx nx affected --base=$NX_BASE --head=$NX_HEAD -t build --parallel=3
49The build and test jobs implement the CI workflow using .distributed as a template to keep the CI configuration file more readable.
Distributed CI with Nx Cloud
Read more about Distributed Task Execution (DTE).
1image: node:18
2
3# Creating template for DTE agents
4.dte-agent:
5  interruptible: true
6  cache:
7    key:
8      files:
9        - yarn.lock
10    paths:
11      - '.yarn-cache/'
12  script:
13    - yarn install --cache-folder .yarn-cache --prefer-offline --frozen-lockfile
14    - yarn nx-cloud start-agent
15
16# Creating template for a job running DTE (orchestrator)
17.base-pipeline:
18  interruptible: true
19  only:
20    - main
21    - merge_requests
22  cache:
23    key:
24      files:
25        - yarn.lock
26    paths:
27      - '.yarn-cache/'
28  before_script:
29    - yarn install --cache-folder .yarn-cache --prefer-offline --frozen-lockfile
30    - NX_HEAD=$CI_COMMIT_SHA
31    - NX_BASE=${CI_MERGE_REQUEST_DIFF_BASE_SHA:-$CI_COMMIT_BEFORE_SHA}
32  artifacts:
33    expire_in: 5 days
34    paths:
35      - dist
36
37# Main job running DTE
38nx-dte:
39  stage: affected
40  extends: .base-pipeline
41  script:
42    - yarn nx-cloud start-ci-run --stop-agents-after="build"
43    - yarn nx-cloud record -- yarn nx format:check --base=$NX_BASE --head=$NX_HEAD
44    - yarn nx affected --base=$NX_BASE --head=$NX_HEAD -t lint --parallel=3 & yarn nx affected --base=$NX_BASE --head=$NX_HEAD -t test --parallel=3 --configuration=ci & yarn nx affected --base=$NX_BASE --head=$NX_HEAD -t e2e --parallel=3 & yarn nx affected --base=$NX_BASE --head=$NX_HEAD -t build --parallel=3
45
46# Create as many agents as you want
47nx-dte-agent1:
48  extends: .dte-agent
49  stage: affected
50nx-dte-agent2:
51  extends: .dte-agent
52  stage: affected
53nx-dte-agent3:
54  extends: .dte-agent
55  stage: affected
56