Sub topic 12
Using scratch orgs in continuous integration
Continuous integration (CI) builds and tests every change automatically. Scratch orgs fit this well. Each run can start from an empty org built from files in version control, and the org can be thrown away afterward. This chapter shows how to build that loop, which limits shape it, and how it fails.
This chapter assumes you know how to create a scratch org from a definition file, how a Dev Hub works, and the basics of Git branches and pull requests. It also assumes you can read a YAML pipeline file.
Why scratch orgs suit CI
A CI job needs an environment that is clean, repeatable, and cheap to discard. Scratch orgs have those properties, and a sandbox has trouble matching them:
- A scratch org starts from the definition file and the source in the repository, so two runs of the same commit begin in the same state.
- Creation takes minutes. You can create one for each pull request instead of sharing one test environment.
- A scratch org expires on its own, so a crashed job does not leave an environment behind for long.
- No production data is involved, so a failed or leaked test run exposes nothing sensitive.
The trade-off is fidelity. A scratch org contains only what you put into it. It does not have your production configuration, your integrations, or realistic data volumes. CI in a scratch org tells you whether the source in the repository deploys and passes its tests from a clean start. It does not tell you how the change behaves against production-like data. A Partial Copy or Full sandbox stage later in the pipeline covers that, as the pipeline chapter describes.
The shape of a CI run
Most scratch org CI jobs follow the same sequence.
The cleanup step runs on both branches. That detail matters later, in the section on limits.
Authorizing the Dev Hub without a browser
On a laptop you authorize the Dev Hub with sf org login web, which opens a browser. A CI runner has no browser, so it uses the JWT bearer flow. JWT is JSON Web Token, a signed token that proves identity without a password prompt.
The setup has three parts:
- Create a certificate and private key. Upload the certificate to a connected app in the Dev Hub org.
- Pre-authorize a user for that connected app, usually with a permission set. The user needs access to the Dev Hub and permission to create scratch orgs.
- Store the private key, the connected app's consumer key, and the Dev Hub username as encrypted secrets in your CI system.
The login command then looks like this:
sf org login jwt \
--client-id "$CLIENT_ID" \
--jwt-key-file server.key \
--username "$DEVHUB_USERNAME" \
--set-default-dev-hub \
--alias devhubAn alternative is sf org login sfdx-url --sfdx-url-file, which uses a stored authorization URL. It is shorter to set up, but the URL contains a refresh token, so treat it as a password. JWT keeps the private key and the user mapping under your control and is the usual choice for shared pipelines.
A complete pull request workflow
The following GitHub Actions workflow validates each pull request against a fresh scratch org. Other CI systems use the same steps with different syntax.
name: validate-pull-request
on:
pull_request:
branches: [main]
jobs:
validate:
runs-on: ubuntu-latest
env:
SCRATCH_ALIAS: ci-${{ github.run_id }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- name: Install Salesforce CLI
run: npm install --global @salesforce/cli
- name: Authorize Dev Hub
env:
JWT_KEY: ${{ secrets.JWT_KEY }}
CLIENT_ID: ${{ secrets.CLIENT_ID }}
DEVHUB_USERNAME: ${{ secrets.DEVHUB_USERNAME }}
run: |
printf '%s' "$JWT_KEY" > server.key
sf org login jwt \
--client-id "$CLIENT_ID" \
--jwt-key-file server.key \
--username "$DEVHUB_USERNAME" \
--set-default-dev-hub \
--alias devhub
rm server.key
- name: Create scratch org
run: |
sf org create scratch \
--definition-file config/project-scratch-def.json \
--alias "$SCRATCH_ALIAS" \
--duration-days 1 \
--wait 15
- name: Deploy source
run: sf project deploy start --target-org "$SCRATCH_ALIAS"
- name: Run Apex tests
run: |
sf apex run test \
--target-org "$SCRATCH_ALIAS" \
--test-level RunLocalTests \
--code-coverage \
--result-format human \
--output-dir test-results \
--wait 30
- name: Save test results
if: always()
uses: actions/upload-artifact@v4
with:
name: test-results
path: test-results
- name: Delete scratch org
if: always()
run: sf org delete scratch --target-org "$SCRATCH_ALIAS" --no-promptSeveral choices in this file are deliberate:
- The alias includes the run ID, so concurrent runs never collide.
--duration-days 1is a backstop. If the runner dies before the delete step, the org still expires within a day.--wait 15makes the create command block until the org is ready or the wait expires. Without it, the next step may start before the org exists.if: always()on the artifact and delete steps makes them run after a failed test step. By default, a failed step skips the steps after it.- The test command returns a nonzero exit code when tests fail, which fails the job and blocks the pull request if you require the check.
Making the scratch org match what the tests expect
Deploying the project source is often not enough. Tests can depend on things that are not in your source folder. Add steps between deploy and test as needed.
| Need | Typical command |
|---|---|
| Packaged dependencies | `sf package install --package <id> --target-org "$SCRATCH_ALIAS" --wait 20` |
| Permissions for the test user | `sf org assign permset --name MyPermSet --target-org "$SCRATCH_ALIAS"` |
| Reference data | `sf data import tree --plan data/plan.json --target-org "$SCRATCH_ALIAS"` |
| Org features and settings | Set them in the definition file, not in the pipeline |
Order matters. Install dependencies before you deploy source that refers to them. Assign permission sets after the source that defines them is deployed. Load data last, after the objects and fields exist.
Keep test data small and committed to the repository as plain files. Apex tests should still create their own records where possible, because tests that rely on loaded data break when someone edits the data files. Use loaded data for things like a reference table that many tests read.
Source tracking in CI
Source tracking records which components changed in an org since you last synced. It is useful on a developer's machine, where you push and pull small changes. A CI job deploys the whole project once to a brand new org, so there is nothing to compare against. Tracking adds nothing in that setting.
Some teams do use tracking-based deployment in long-lived CI orgs to deploy only the changes since the last run. This is a different pattern with its own risks, such as drift between the tracked state and the repository. The one-org-per-run pattern in this chapter avoids those risks.
Managing limits
A Dev Hub limits how many scratch orgs can be active at once, and how many can be created per day. The exact numbers depend on the Dev Hub's edition and are described in the limits chapter. A busy repository can hit them, because every push to every pull request may create an org.
Check the current usage from the pipeline or from a terminal:
sf org list limits --target-org devhubLook for ActiveScratchOrgs and DailyScratchOrgs in the output. Each shows the remaining count and the maximum.
Ways to stay under the limits:
- Always delete the org at the end of the job, including after failures.
- Run the scratch org job only on pull requests that change Salesforce source, using path filters.
- Cancel outdated runs when a new commit lands on the same pull request, so the old run's org is released.
- Run the cheap checks first, such as formatting and static analysis, and create the org only if they pass.
- Run the full scratch org validation on pull requests to the main branch, not on every branch push.
Speeding up runs
Creating an org and deploying a large project can take many minutes. These approaches reduce that time:
- Keep the definition file small. Every feature and setting you enable adds creation time.
- Use scratch org snapshots, if your Dev Hub supports them, to start from an org that already has the slow setup done, such as installed packages. Snapshots become stale when the underlying setup changes, so rebuild them on a schedule.
- Split a large codebase into packages, and validate only the package a pull request touches.
- Run test classes in parallel where the tooling allows it. Tests that depend on shared record state may fail when run in parallel, so fix those first.
Common failures
| Symptom | Likely cause |
|---|---|
| Login step fails with a user-not-approved error | The user is not pre-authorized for the connected app |
| Create step fails with a limit error | The active or daily scratch org limit is reached |
| Deploy fails on missing components | A dependency or feature is not in the org. Check the install order and the definition file |
| Tests pass in the pipeline and fail in the sandbox | The scratch org lacks the data volume or configuration of the sandbox |
| Tests pass locally and fail in CI | A test depends on data or a permission that exists only in the developer's org |
| Orgs pile up in the Dev Hub | The delete step was skipped after a failure. Add `if: always()` |
Summary of the pattern
Authorize the Dev Hub with JWT. Create one short-lived scratch org per run. Deploy the project, add dependencies and test data, and run the tests. Save the results and always delete the org. Watch the Dev Hub limits. Treat a green scratch org run as proof that the source works from a clean start, and rely on later pipeline stages for production-like checks.
Exercise
A pull request pipeline creates a scratch org, deploys source, and runs tests, then deletes the org in the final step. After a week, the Dev Hub shows many active scratch orgs from failed runs. What is the cause, and what two changes would prevent the buildup?
Show answer
When the test step fails, the pipeline stops and skips the later delete step, so the org stays active until it expires. Mark the delete step to run even after failures (for example if: always() in GitHub Actions). Also create the org with a short --duration-days value, such as 1, so any org that is still orphaned expires soon.
Exercise
Your team hits the daily scratch org creation limit by mid-afternoon, even though every job deletes its org. Why does deleting not fix it, and name two ways to reduce creations?
Show answer
Deleting an org frees an active slot but does not restore the daily creation count. To create fewer orgs, run the scratch org job only when Salesforce source changes (path filters), run cheap checks first and create the org only if they pass, or cancel outdated runs when a new commit arrives on the same pull request.