Sub topic 16
Automating Package Builds in CI
This chapter assumes you can already build a package version by hand with sf package version create, and that you know what beta and released versions are. Here you move those manual steps into a continuous integration (CI) pipeline. The pipeline builds a version on every change, checks that it installs, and promotes it only when you decide to.
What CI should do for a managed package
A managed package build is slow and costs Dev Hub resources. Each package version counts against a daily limit on your Dev Hub, and each build runs your Apex tests. Design the pipeline around those two facts.
A practical pipeline has three stages:
- Validate on every pull request. Build a version with code coverage, install it into a fresh scratch org, and run checks against it.
- Build on merge to the main branch. Create the version that could become a release candidate, and record its ID.
- Promote on demand. Run
sf package version promoteonly from a protected trigger, such as a release tag or a manually approved job.
Authenticating without a browser
sf org login web needs a person at a browser, so CI cannot use it. Use the JWT bearer flow instead. You need three things:
- A connected app in the Dev Hub org, with a certificate uploaded and the pipeline's user pre-authorized.
- The matching private key, stored as a CI secret.
- The consumer key of the connected app, stored as a secret too.
echo "$SF_JWT_KEY" > server.key
sf org login jwt \
--client-id "$SF_CLIENT_ID" \
--jwt-key-file server.key \
--username "$SF_DEVHUB_USER" \
--instance-url https://login.salesforce.com \
--set-default-dev-hub \
--alias devhub
rm server.keyRemove the key file when you are done. Never print the secret, and do not run the pipeline with shell tracing (set -x) enabled while it is in scope.
An alternative is sf org login sfdx-url --sfdx-url-file, which uses a stored auth URL. It is simpler to set up, but the auth URL carries a refresh token. Treat it with the same care as a password.
Building the version and capturing its ID
Add --json so the pipeline can read the result instead of parsing text. The build command exits with a non-zero code when the build fails, so the job fails by default.
sf package version create \
--package AcmeApp \
--installation-key-bypass \
--code-coverage \
--branch "$GITHUB_REF_NAME" \
--wait 30 \
--target-dev-hub devhub \
--json > build.json
jq -r '.result.SubscriberPackageVersionId' build.jsonThe value that starts with 04t is the subscriber package version ID. It is the stable handle you pass to install and promote steps in later jobs.
Three details matter here:
--code-coverageis required for a releasable version. Without it, or with--skip-validation, the version cannot be promoted.--skip-validationis fine for a fast inner-loop build, but never for a release candidate.--branchtags the version with its source branch. Use it so you can find and list versions by branch later.--waitneeds headroom. Large packages can take longer than the 20 minutes shown in earlier chapters. If the wait expires, the build keeps running on the server. Check on it withsf package version create report.
Keep versionNumber in sfdx-project.json set to a .NEXT build number, such as 1.1.0.NEXT. The platform then assigns the build number, and two parallel pipeline runs never collide on the same version.
Verifying the version in a scratch org
Version creation already runs your packaged Apex tests. The scratch-org stage proves something different: that the built artifact installs cleanly and works in a new org.
sf org create scratch \
--definition-file config/project-scratch-def.json \
--alias ci-test \
--duration-days 1 \
--wait 10 \
--target-dev-hub devhub
sf package install \
--package "$VERSION_ID" \
--target-org ci-test \
--wait 10 \
--no-prompt
sf org delete scratch --target-org ci-test --no-promptNote that sf apex run test --test-level RunLocalTests skips tests that belong to installed managed packages. Running it after the install does not re-run your package's own tests. Use this stage for tests that live outside the package, such as integration tests kept in a separate, unpackaged directory. Always delete the scratch org, even when an earlier step failed, or you will exhaust your active scratch org limit.
A complete GitHub Actions workflow
This workflow validates pull requests. Adapt the syntax for another CI system. The commands stay the same.
name: package-validate
on:
pull_request:
branches: [main]
jobs:
validate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Salesforce CLI
run: npm install --global @salesforce/cli
- name: Authorize Dev Hub
env:
SF_JWT_KEY: ${{ secrets.SF_JWT_KEY }}
run: |
echo "$SF_JWT_KEY" > server.key
sf org login jwt \
--client-id "${{ secrets.SF_CLIENT_ID }}" \
--jwt-key-file server.key \
--username "${{ secrets.SF_DEVHUB_USER }}" \
--set-default-dev-hub \
--alias devhub
rm server.key
- name: Build package version
id: build
run: |
sf package version create --package AcmeApp \
--installation-key-bypass --code-coverage \
--branch "${{ github.head_ref }}" --wait 30 \
--target-dev-hub devhub --json > build.json
echo "version_id=$(jq -r '.result.SubscriberPackageVersionId' build.json)" >> "$GITHUB_OUTPUT"
- name: Create scratch org and install
run: |
sf org create scratch --definition-file config/project-scratch-def.json \
--alias ci-test --duration-days 1 --wait 10 --target-dev-hub devhub
sf package install --package "${{ steps.build.outputs.version_id }}" \
--target-org ci-test --wait 10 --no-prompt
- name: Delete scratch org
if: always()
run: sf org delete scratch --target-org ci-test --no-prompt || trueGating promotion
Promotion cannot be undone. A released version can never go back to beta, and you cannot delete it. Keep the promote step out of the pull request workflow. Run it from a separate job that requires an approval, such as a protected environment, and that targets a version ID you already built and tested:
sf package version promote --package "$VERSION_ID" --no-prompt --target-dev-hub devhubPromote the exact version you tested. Do not rebuild at release time, because a rebuild produces a different build number and different contents.
Common failures
| Symptom | Likely cause | Fix |
|---|---|---|
| Login fails with a pre-authorization error | The connected app does not list the pipeline user | Pre-authorize the user's profile or a permission set on the connected app |
| Build job times out but version appears later | `--wait` was shorter than the build | Raise `--wait`, or poll with `sf package version create report` |
| Promote fails on coverage | The version was built with `--skip-validation` or below 75% coverage | Rebuild with `--code-coverage` and fix tests |
| Scratch org creation fails | Active scratch org limit reached | Delete orgs in an `if: always()` step |
| Two runs produce confusing versions | Parallel builds on one branch | Tag with `--branch` and list with `sf package version list --branches` |
Exercise
A teammate proposes rebuilding the package at release time with sf package version create and then promoting the new version, "to be sure it is fresh." Give two reasons this is worse than promoting the version CI already tested.
Show answer
First, the rebuild creates a different version, with a new build number and possibly different source, so the artifact you promote was never the one you validated in the scratch org. Second, it uses another build against the Dev Hub's daily version limit and repeats a slow test run. The safer pattern is to store the 04t version ID from the tested build and promote that ID after approval.