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 # This line enables distribution 13 # The "--stop-agents-after" is optional, but allows idle agents to shut down once the "e2e-ci" targets have been requested 14 - npx nx-cloud start-ci-run --distribute-on="3 linux-medium-js" --stop-agents-after="e2e-ci" 15 - npm ci 16 17 # Prepend any command with "nx-cloud record --" to record its logs to Nx Cloud 18 # This requires connecting your workspace to Nx Cloud. Run "nx connect" to get started w/ Nx Cloud 19 # - npx nx-cloud record -- nx format:check 20 21 # Without Nx Cloud, run format:check directly 22 - npx nx format:check 23 - npx nx affected -t lint test build e2e-ci --base=origin/main 24 25 branches: 26 main: 27 - step: 28 name: "Build and test affected apps on 'main' branch changes" 29 script: 30 - export NX_BRANCH=$BITBUCKET_BRANCH 31 # This line enables distribution 32 # The "--stop-agents-after" is optional, but allows idle agents to shut down once the "e2e-ci" targets have been requested 33 # - npx nx-cloud start-ci-run --distribute-on="3 linux-medium-js" --stop-agents-after="e2e-ci" 34 - npm ci 35 36 # Prepend any command with "nx-cloud record --" to record its logs to Nx Cloud 37 # This requires connecting your workspace to Nx Cloud. Run "nx connect" to get started w/ Nx Cloud 38 # - npx nx-cloud record -- nx format:check 39 40 # Without Nx Cloud, run format:check directly 41 - npx nx format:check 42 - npx nx affected -t lint test build e2e-ci --base=HEAD~1 43

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.