Sub topic 15
Wiring seeding into a setup script and CI
Earlier chapters covered the individual seeding tools: tree export and import, bulk upsert, Apex scripts, and post-copy classes. This chapter combines them into one script that a developer runs locally and a CI job runs on every pull request.
This chapter assumes you can already:
- create a scratch org with
sf org create scratch - import a dataset with a plan file
- read basic Bash
- read a short YAML workflow
What the automation must guarantee
A seeding script is only useful if anyone can run it and get the same org. Aim for these properties:
- One command. A new teammate runs a single script, with no checklist of manual steps.
- Fixed order. Metadata deploys before data, and parent records load before children.
- Fail fast. The script stops at the first error. A half-seeded org is worse than no org.
- Safe to repeat. Running it twice either rebuilds the org or leaves the data unchanged.
- No secrets in the repository. Credentials come from the environment.
The order of operations
The order is the same locally and in CI. Only the authentication step differs.
Metadata must come first because the import fails if the objects and fields don't exist. Permission sets come before data, because field-level security can hide fields that the import needs to write. Verification comes last, so the script fails loudly when seeding silently produced nothing.
A reusable setup script
Save this as scripts/setup-org.sh. It uses only commands from this tutorial plus jq for reading JSON output.
#!/usr/bin/env bash
set -euo pipefail
ALIAS="${1:-my-scratch}"
DAYS="${2:-7}"
echo "Creating scratch org ${ALIAS}..."
sf org create scratch \
--definition-file config/project-scratch-def.json \
--alias "${ALIAS}" \
--set-default \
--duration-days "${DAYS}" \
--wait 10
echo "Deploying metadata..."
sf project deploy start --target-org "${ALIAS}"
echo "Importing tree data..."
sf data import tree \
--plan data/Account-Contact-plan.json \
--target-org "${ALIAS}"
echo "Upserting bulk data..."
sf data upsert bulk \
--sobject Account \
--file data/accounts.csv \
--external-id External_Id__c \
--target-org "${ALIAS}" \
--wait 10
echo "Running Apex seed script..."
sf apex run --file scripts/apex/seed.apex --target-org "${ALIAS}"
echo "Verifying..."
COUNT=$(sf data query \
--query "SELECT COUNT() FROM Account" \
--target-org "${ALIAS}" \
--json | jq -r '.result.totalSize')
if [ "${COUNT}" -lt 1 ]; then
echo "Seeding failed: no Account records found." >&2
exit 1
fi
echo "Done. ${COUNT} Accounts in ${ALIAS}."Three lines in this script do most of the work:
set -euo pipefailmakes Bash exit when any command fails, when a variable is unset, or when any command in a pipeline fails. Without it, a failed import would be followed by a cheerful "Done."--wait 10makes the CLI block for up to ten minutes, so later steps don't run against an org that is still being created or a bulk job that is still running.- The
COUNT()query returns its count inresult.totalSizewhen you use--json. Checking that value is a cheap smoke test.
If your scratch org needs permission sets, add sf org assign permset --name YOUR_PERMSET --target-org "${ALIAS}" between the deploy and the import. Use the API name of a permission set in your project.
Making the script safe to run twice
The script above is idempotent in the simplest way. The org it seeds is brand new each time, so there is nothing to duplicate. This is the approach to prefer for scratch orgs.
Sometimes you want to reseed an existing org instead, because the org takes a long time to build or you are working in a sandbox. The commands behave differently when repeated:
| Step | Safe to repeat? | Why |
|---|---|---|
| `sf project deploy start` | Yes | Deploying the same metadata is a no-op or an update. |
| `sf data upsert bulk` with an external ID | Yes | Existing rows are updated, and no duplicates are created. |
| `sf data import tree` | No | It always inserts, so each run creates duplicate records. |
| Anonymous Apex that calls `insert` | No | It inserts every time it runs. |
To reseed an existing org, guard the non-idempotent steps with a check:
EXISTING=$(sf data query \
--query "SELECT COUNT() FROM Account WHERE Name = 'Seed Account'" \
--target-org "${ALIAS}" \
--json | jq -r '.result.totalSize')
if [ "${EXISTING}" -eq 0 ]; then
sf apex run --file scripts/apex/seed.apex --target-org "${ALIAS}"
else
echo "Seed Account already exists, skipping Apex seed."
fiA better long-term fix is to change the data. Put external IDs on every seeded object and use upsert wherever you can. Then the guard is unnecessary.
Authenticating in CI
A CI runner has no browser, so you can't use the interactive web login. Use an SFDX auth URL, which is a single string that encodes the refresh token for an org.
- On your machine, authorize the Dev Hub normally.
- Run
sf org display --target-org YOUR_DEVHUB --verbose --jsonand copy thesfdxAuthUrlvalue. - Store it as an encrypted secret in your CI system, for example
DEVHUB_SFDX_URL.
A CI workflow
This GitHub Actions workflow runs the same script on every pull request. The if: always() condition on the last step deletes the scratch org even when an earlier step fails, so failed runs don't consume your active scratch org limit.
name: Seed and test
on:
pull_request:
jobs:
seed-and-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Salesforce CLI
run: npm install --global @salesforce/cli
- name: Authenticate to Dev Hub
env:
DEVHUB_SFDX_URL: ${{ secrets.DEVHUB_SFDX_URL }}
run: |
echo "${DEVHUB_SFDX_URL}" > "${RUNNER_TEMP}/devhub.txt"
sf org login sfdx-url \
--sfdx-url-file "${RUNNER_TEMP}/devhub.txt" \
--alias devhub \
--set-default-dev-hub
rm "${RUNNER_TEMP}/devhub.txt"
- name: Create and seed scratch org
run: ./scripts/setup-org.sh ci-scratch 1
- name: Run Apex tests
run: sf apex run test --target-org ci-scratch --wait 20 --result-format human
- name: Delete scratch org
if: always()
run: sf org delete scratch --target-org ci-scratch --no-promptNote the argument 1 passed to the script. CI orgs are disposable, so a one-day duration is enough. If cleanup ever fails, the org still expires on its own.
Failure modes in automation
- Script is not executable. If the runner reports "permission denied", run
chmod +x scripts/setup-org.shand commit the change. Git records the executable bit. - Scratch org limits. Each Dev Hub has daily and active scratch org limits. Many parallel pull requests can exhaust them, so always delete orgs in cleanup.
- Stale data files. A plan file that references a field you renamed fails during import. Because the import happens in CI on every pull request, you find this when the change is made rather than weeks later.
- Order bugs hidden by an existing org. A script that works against your long-lived org may fail on a fresh one, because it depended on metadata that was deployed by hand. Fresh orgs in CI expose this.
- Sandboxes are different. You don't create sandboxes per pull request. For sandboxes, rely on the sandbox template and the
SandboxPostCopyclass, and use the same scripts only for manual top-up seeding with upsert.
Exercise
Your CI job creates a scratch org, imports the tree plan, and runs Apex tests. A teammate proposes re-running the same job against a long-lived shared scratch org to save creation time. What breaks first, and how would you change the seeding steps to make it work?
Show answer
The tree import breaks first. sf data import tree always inserts, so each run adds duplicate Accounts and Contacts, which can cause tests that count records or look up by name to fail. To make the job safe to repeat, add an external ID field to the seeded objects and load them with sf data upsert bulk, or guard the import with a COUNT() query that skips seeding when the seed records already exist. Also keep set -euo pipefail so any failure still stops the job.