Sub topic 16
Running retrieve and deploy in scripts and CI
This chapter assumes you can already run sf project retrieve start, sf project deploy start, and the validate and quick-deploy pair by hand. It also assumes you know the basics of Git and a CI service such as GitHub Actions. The goal is to move those commands from your terminal into unattended jobs that fail loudly and never depend on a person.
What changes when no one is watching
A script has no browser, no default org, and no one to read an error. Each of these needs an explicit answer.
| Interactive habit | Unattended replacement |
|---|---|
| `sf org login web` | JWT login or an SFDX auth URL |
| `sf config set target-org` | `--target-org` on every command |
| Reading terminal output | `--json` plus an exit code check |
| Waiting at the prompt | `--wait` with a fixed number of minutes |
| Local keychain | A CI secret store |
Authorize without a browser
The usual choice for CI is the JWT bearer flow. You create a connected app in the org, upload a certificate, and keep the matching private key as a CI secret. The runner then logs in with the key and never opens a browser.
sf org login jwt \
--client-id "$SF_CLIENT_ID" \
--jwt-key-file server.key \
--username "$SF_USERNAME" \
--instance-url https://login.salesforce.com \
--alias ci-orgUse https://test.salesforce.com as the instance URL for a sandbox. A My Domain URL also works.
The alternative is an SFDX auth URL. On your own machine, run sf org display --verbose --json for an org you already authorized. Copy the sfdxAuthUrl value into a secret. The job writes it to a file and logs in with sf org login sfdx-url --sfdx-url-file auth.txt --alias ci-org. This is quick to set up, but the URL contains a refresh token. Treat it like a password and delete the file after login.
On Linux runners without a keyring, the CLI may fail when it stores credentials. Setting SF_USE_GENERIC_UNIX_KEYCHAIN=true makes it use a file-based store instead. Setting SF_AUTOUPDATE_DISABLE=true stops the CLI from updating itself mid-job.
Always name the target org
On your laptop, sf config set target-org saves you typing. In a script it is a hidden dependency. A leftover config value on a shared runner can send a deploy to the wrong org. Pass --target-org ci-org on every command, and never rely on a default.
Machine-readable output and exit codes
Add --json to any sf command. The CLI then prints one JSON document with a status field and a result object, and it exits non-zero on failure. Those two signals are what a script should act on. Do not grep human-readable text, because its wording can change between CLI versions.
Shell scripts have a trap here. With set -e, a failing command inside $(...) aborts the script before you can read the JSON that explains the failure. Wrap the call in an if so you can print the failure details first.
#!/usr/bin/env bash
set -euo pipefail
ORG_ALIAS="ci-org"
if ! result=$(sf project deploy validate \
--manifest manifest/package.xml \
--target-org "$ORG_ALIAS" \
--test-level RunLocalTests \
--wait 60 \
--json); then
echo "Validation failed. Component failures:" >&2
echo "$result" | jq '.result.details.componentFailures // .message' >&2
exit 1
fi
echo "$result" | jq -r '.result.id' > validated-job-id.txt
echo "Validated job: $(cat validated-job-id.txt)"This script needs jq, which GitHub-hosted Linux runners include. The job ID goes into a file so a later step can quick-deploy it.
Waiting, timeouts, and resuming
--wait sets how many minutes the command blocks before it stops waiting. Stopping the wait does not stop the deployment. The server keeps working, and the command exits with a non-zero status that signals "still in progress". Set --wait high enough for your test suite, then handle the timeout case on purpose:
- Run the deploy with
--wait 30. - If it times out, run
sf project deploy resume --job-id <id> --wait 30. - If it still does not finish, run
sf project deploy cancel --job-id <id>and fail the job.
Always capture the job ID from the --json output (.result.id) rather than using --use-most-recent. In --use-most-recent mode, the CLI reads a cache on the current machine. A fresh CI runner has no such cache, and a shared runner might have another job's entry.
A validate-then-quick-deploy pipeline
The pattern from the quick-deploy chapter fits CI well. Validate when a pull request opens, so reviewers see a real result from the target org. When the change merges, quick-deploy the validated job instead of running the tests again.
A quick deploy only works if the validation succeeded with the required tests and is recent. The window is 10 days. If the job ID has expired, or the merged code differs from what you validated, the quick deploy fails. Have the pipeline fall back to sf project deploy start --test-level RunLocalTests. For a production org, the fallback must still run tests.
The job ID has to survive between the pull request run and the merge run. Store it as a build artifact, a CI cache entry, or a comment on the pull request. A common alternative is to skip the saved ID and validate again on the merge commit. That costs one more test run but removes the problem of tying an ID to an exact commit.
A GitHub Actions workflow
This workflow validates every pull request against a sandbox. It writes the private key from a secret to a file, runs the validation, and deletes the key.
name: validate-metadata
on:
pull_request:
branches: [main]
jobs:
validate:
runs-on: ubuntu-latest
env:
SF_USE_GENERIC_UNIX_KEYCHAIN: "true"
SF_AUTOUPDATE_DISABLE: "true"
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 org
env:
JWT_KEY: ${{ secrets.SF_JWT_KEY }}
run: |
printf '%s' "$JWT_KEY" > server.key
sf org login jwt \
--client-id "${{ secrets.SF_CLIENT_ID }}" \
--jwt-key-file server.key \
--username "${{ secrets.SF_USERNAME }}" \
--instance-url https://test.salesforce.com \
--alias ci-org
rm -f server.key
- name: Validate deployment
run: |
sf project deploy validate \
--manifest manifest/package.xml \
--target-org ci-org \
--test-level RunLocalTests \
--wait 60In a real project, pin the CLI version (for example @salesforce/[email protected]) so a new release cannot change behavior between runs.
Scripting retrieves
Retrieve jobs are common in scheduled pipelines. A nightly job retrieves from a sandbox and commits the difference as a backup, or opens a pull request. The main points:
- Retrieve by manifest (
--manifest), so the job pulls the same components every night. - Run
git status --porcelainafterward. Empty output means nothing changed, so the job can skip the commit. - Keep
.forceignorein the repository. Without it, noisy files such as profiles with user-specific settings show up as diffs every night. - Retrieves from a sandbox without source tracking are not affected by conflict checks. Use a full manifest rather than tracking state.
Choosing flags for automation
- Test level. Use
RunLocalTestsfor validation against production-like orgs. UseRunSpecifiedTestswith--testsfor fast feedback on a scratch org. UseNoTestRunonly for sandboxes and scratch orgs, because production rejects it for Apex deployments. - Conflicts.
--ignore-conflictsskips the tracking conflict check. Use it only in a throwaway org that your pipeline fully owns, never to silence a real conflict in a shared environment. - Secrets. Never echo them, and do not enable shell tracing (
set -x) around login steps.
Common failures in CI
No authorization information found for ci-org: the login step ran in a different job or runner than the deploy step. Log in again in each job.- Validation passes locally but fails in CI: the CI org has different data, or a test relies on a setting in your org. Run the same
--test-levellocally first. - Quick deploy says the job cannot be found or is not valid: the job is older than 10 days, ran against a different org, or did not run the required tests.
- The job hangs: the CLI is waiting on a prompt. Pass
--jsonor confirm the command has all required flags.
Exercise
A script runs result=$(sf project deploy start --manifest manifest/package.xml --target-org ci-org --json) under set -e. The deploy fails, but the log shows no error details. Why, and how do you fix it?
Show answer
The command substitution returns a non-zero status, so set -e ends the script before it can print $result. Wrap the call in if ! result=$(...); then, print the JSON (for example .result.details.componentFailures // .message through jq) to stderr, and then exit 1.
Exercise
Your pipeline validates on a pull request and quick-deploys on merge. The merge job reports that the validated job cannot be used. Name two likely causes and one fallback.
Show answer
Likely causes are that the job is more than 10 days old, or that the saved job ID came from a different org or a different set of code than the one being deployed. Another is that the validation did not run the required tests. The fallback is a full sf project deploy start --test-level RunLocalTests.