Sub topic 17
Package Workflows in CI/CD
This chapter assumes you can create a package and a package version with the Salesforce CLI, that you know what a Dev Hub and a scratch org are, and that you have used Git branches and pull requests. It shows how to run the package lifecycle from a pipeline instead of from a developer's laptop.
Why automate the package lifecycle
Creating a package version by hand works for a first experiment. It breaks down once several people change the same project. Two developers can build versions from different branches, a version can be promoted without passing tests, and nobody can say which version is in production.
A pipeline fixes this by making every step repeatable and tied to a Git event. A pull request builds and tests. A merge to the main branch creates a candidate version. A release step promotes that version and installs it. Each step uses the same commands you already know.
The stages of a package pipeline
A typical pipeline has four stages. Each one answers a different question.
| Stage | Trigger | Question it answers | Main command |
|---|---|---|---|
| Validate | Pull request | Does the change build as a package version? | `sf package version create` |
| Test install | Pull request or merge | Does the version install and work in a clean org? | `sf package install` into a scratch org |
| Publish | Merge to main | Can we keep this version as a release candidate? | `sf package version create` with coverage |
| Release | Manual approval or tag | Is it ready for production? | `sf package version promote`, then `sf package install` |
Authenticating the pipeline
The pipeline needs access to the Dev Hub and to each target org. Do not store a password. Use the JWT bearer flow, which authenticates with a connected app, a certificate and a username.
Store the private key and the consumer key as secrets in your CI system. The pipeline writes the key to a temporary file and logs in:
echo "$SF_JWT_KEY" > server.key
sf org login jwt \
--client-id "$SF_CONSUMER_KEY" \
--jwt-key-file server.key \
--username "$SF_DEVHUB_USER" \
--alias MyDevHub \
--set-default-dev-hub
rm server.keyThe Dev Hub user needs permission to create package versions. For production installs, use a separate connected app and user with the least access that still allows package installation.
Validating on a pull request
The validation job proves that the package can be built. Create a version on every pull request, and skip nothing that affects correctness.
sf package version create \
--package Core \
--installation-key-bypass \
--wait 30 \
--target-dev-hub MyDevHub \
--json > version-result.jsonThe --json flag makes the output easy to parse in a script. A failed build returns a non-zero exit code, so the CI job fails without extra logic.
Two flags matter for speed:
--skip-validationcreates the version faster by skipping the dependency and metadata checks. Such a version cannot be promoted, so use it only for quick feedback builds, never for release candidates.--code-coverageruns the Apex tests during the build and records coverage. A version needs this before it can be promoted, so use it on the merge build.
Version creation counts against Dev Hub limits on daily package version creations. Check your allowance with sf limits api display --target-org MyDevHub and look for the package version limit. Building on every commit of every branch can exhaust it.
Building only what changed
A project with many packages should not rebuild all of them on every change. The sf package version create command works on one package at a time, so the pipeline decides which packages to build.
One approach is to compare changed paths against the package directories in sfdx-project.json. The script below prints the packages whose directories contain changes since the main branch.
import json
import subprocess
def changed_packages(base="origin/main"):
with open("sfdx-project.json") as f:
project = json.load(f)
diff = subprocess.run(
["git", "diff", "--name-only", base, "HEAD"],
capture_output=True, text=True, check=True,
).stdout.splitlines()
changed = []
for directory in project["packageDirectories"]:
path = directory["path"].rstrip("/") + "/"
if any(name.startswith(path) for name in diff):
changed.append(directory["package"])
return changed
if __name__ == "__main__":
for name in changed_packages():
print(name)This has a gap. If Core changes, Sales depends on it and may need a new build too. Extend the script to also include any package that lists a changed package under dependencies. Build the packages in dependency order, with Core first.
Handling dependencies between versions
Our Sales package depends on Core at 1.0.0.LATEST. In a pipeline this has a consequence. When Core and Sales change in the same pull request, Sales must build against the new Core version, not an older one.
Build Core first and then resolve its new version ID. The sf package version list command shows built versions:
sf package version list \
--packages Core \
--concise \
--order-by CreatedDate \
--target-dev-hub MyDevHubYou can also pin a dependency to a specific version in sfdx-project.json for release builds, for example [email protected]. Pinning removes surprises, because a LATEST reference can pick up a version that was built after you tested. The cost is an extra edit each time Core changes.
For a pipeline, a common rule is to use LATEST on feature branches and pinned versions on the release branch.
Installing into scratch orgs and sandboxes
The test-install stage proves the package works outside the project it was built from. The job creates a scratch org, installs dependencies and the new version, then runs tests that exercise the installed result.
sf org create scratch \
--definition-file config/project-scratch-def.json \
--alias ci-scratch \
--duration-days 1 \
--target-dev-hub MyDevHub
sf package install \
--package "[email protected]" \
--target-org ci-scratch \
--wait 20 \
--no-prompt
sf apex run test \
--target-org ci-scratch \
--test-level RunLocalTests \
--wait 20 \
--result-format human
sf org delete scratch --target-org ci-scratch --no-promptSet --duration-days 1 so an abandoned scratch org expires quickly. Delete the org at the end of the job. Put the delete step in an "always run" block, so a failed test does not leave orgs behind.
The --no-prompt flag skips the confirmation prompt, which would otherwise hang a non-interactive job.
Promotion and release
Promotion marks a version as released. It cannot be undone, and only a promoted version can be installed in production. This is why it belongs behind an approval.
Use these rules for the release stage:
- Promote only a version that was created with
--code-coverageand passed the 75% threshold. - Promote the exact version that was tested in the sandbox. Do not build a new version at release time.
- Require a human approval, such as a protected environment in your CI system.
- Record the version ID and the Git commit in the release notes.
sf package version promote \
--package "[email protected]" \
--no-prompt \
--target-dev-hub MyDevHub
sf package install \
--package "[email protected]" \
--target-org MyProdOrg \
--wait 30 \
--no-promptIf the package has dependencies, install them in order. sf package install installs only the package you name, so the release job must install Core before Sales. Use the order in sfdx-project.json as the source of truth.
Common errors
- The build times out. The
--waitvalue is only how long the CLI waits, not how long the build takes. The build continues on the server. Usesf package version create report --package-create-request-id 08c...to read its status. - Promotion fails with a coverage error. The version was built without
--code-coverage, or coverage is under 75%. Build a new version. You cannot add coverage to an existing one. - Install fails because of a missing dependency. The target org lacks the package that yours depends on. Install the dependency first.
- The version number does not increase.
NEXTincrements the build number only. Change the major, minor or patch number insfdx-project.jsonwhen you want a new release line. - The pipeline commits
sfdx-project.jsonchanges. Creating a version adds apackageAliasesentry. Commit that change back to the repository, or later jobs will not find the alias.
Exercises
Exercise
A pull request builds a package version with --skip-validation to save time. After merge, the release job tries to promote that version. What happens, and what should the pipeline do instead?
Show answer
The promotion fails, because a version created with --skip-validation cannot be promoted. The merge build should create a new version without --skip-validation and with --code-coverage, and the release job should promote that version.
Exercise
Why should the release job promote the version that was tested in the sandbox instead of building a fresh version from the same commit?
Show answer
A fresh build is a different version, even from the same commit. It could resolve LATEST dependencies differently, and it has not been through the sandbox tests. Promoting the tested version means production receives exactly what was verified.