Configuring CI Using Bitbucket Pipelines and Nx
Below is an example of a Bitbucket Pipelines, building and testing only what is affected.
bitbucket-pipelines.yml
1image: node:20
2
3clone:
4 depth: full
5
6pipelines:
7 pull-requests:
8 '**':
9 - step:
10 name: 'Build and test affected apps on Pull Requests'
11 script:
12 - export NX_BRANCH=$BITBUCKET_PR_ID
13
14 # This enables task distribution via Nx Cloud
15 # Run this command as early as possible, before dependencies are installed
16 # Learn more at https://nx.dev/ci/reference/nx-cloud-cli#npx-nxcloud-startcirun
17 # Connect your workspace by running "nx connect" and uncomment this line to enable task distribution
18 # - npx nx start-ci-run --distribute-on="3 linux-medium-js" --stop-agents-after="build"
19
20 - npm ci --legacy-peer-deps
21
22 # Prepend any command with "nx-cloud record --" to record its logs to Nx Cloud
23 # npx nx-cloud record -- echo Hello World
24 - npx nx affected --base=origin/main -t lint test build
25 # Nx Cloud recommends fixes for failures to help you get CI green faster. Learn more: https://nx.dev/ci/features/self-healing-ci
26
27 after-script:
28 - npx nx fix-ci
29
30 branches:
31 main:
32 - step:
33 name: 'Build and test affected apps on "main" branch changes'
34 script:
35 - export NX_BRANCH=$BITBUCKET_BRANCH
36 # This enables task distribution via Nx Cloud
37 # Run this command as early as possible, before dependencies are installed
38 # Learn more at https://nx.dev/ci/reference/nx-cloud-cli#npx-nxcloud-startcirun
39 # Connect your workspace by running "nx connect" and uncomment this
40 # - npx nx start-ci-run --distribute-on="3 linux-medium-js" --stop-agents-after="build"
41
42 - npm ci --legacy-peer-deps
43
44 # Prepend any command with "nx-cloud record --" to record its logs to Nx Cloud
45 # - npx nx-cloud record -- echo Hello World
46 - npx nx affected -t lint test build --base=HEAD~1
47
The pull-requests
and main
jobs implement the CI workflow.
Get 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.