Sub topic 14
Automating recurring exports
A backup you run by hand gets skipped. This chapter turns the Salesforce CLI export from earlier chapters into a job that runs on a schedule, handles authentication without a person present, and reports failures. It assumes you can run sf data query, write SOQL, and use a terminal and a scheduler such as cron or a CI system.
What automation has to solve
A one-off export only needs a query. A recurring export also needs answers to these questions:
- How does the job log in without a person typing a password?
- Where does each run write its files, so that runs do not overwrite each other?
- How does the job tell you when it fails?
- How does it avoid exporting everything every time?
Authenticating without a person
The CLI commands in this tutorial use an org alias such as my-prod-alias. The alias points at a stored authorization. For an unattended job, authorize once with a method that does not need a browser at run time. The JWT bearer flow is the usual choice. It uses a connected app, a certificate, and a named integration user.
sf org login jwt \
--client-id "$SF_CLIENT_ID" \
--jwt-key-file server.key \
--username [email protected] \
--alias my-prod-alias \
--set-defaultUse a dedicated integration user for backups, not a personal account. Give that user read access to the objects and fields you export, and nothing more. Keep server.key and the client ID in your scheduler's secret store, not in the script or the repository.
A dated export script
The script below writes one CSV per object into a folder named for the day. It extends the earlier example with a log file, a check that each file is not empty, and a non-zero exit code on any failure, which schedulers use to detect a failed run.
#!/usr/bin/env bash
set -euo pipefail
ORG="my-prod-alias"
STAMP="$(date +%Y%m%d)"
DEST="backup/$STAMP"
LOG="$DEST/export.log"
mkdir -p "$DEST"
for OBJ in Account Contact Opportunity; do
echo "$(date -u +%FT%TZ) exporting $OBJ" >> "$LOG"
sf data query \
--query "SELECT Id, Name FROM $OBJ" \
--result-format csv \
--target-org "$ORG" > "$DEST/$OBJ.csv"
ROWS=$(( $(wc -l < "$DEST/$OBJ.csv") - 1 ))
if [ "$ROWS" -lt 1 ]; then
echo "$(date -u +%FT%TZ) $OBJ exported no rows" >> "$LOG"
exit 1
fi
echo "$(date -u +%FT%TZ) $OBJ rows=$ROWS" >> "$LOG"
doneThree details matter here:
set -euo pipefailstops the script at the first failed command. Withoutpipefail, a failure inside a pipeline can go unnoticed.- The row count is the number of lines minus the header. Fields that contain line breaks make this count too high, so treat it as a rough check and use
SELECT COUNT()for a precise comparison. Namedoes not exist on every object. Task, for example, has noNamefield. Replace the field list with the fields each object really has.
Exporting only what changed
A full export of every object each night wastes API calls and time. After one full baseline, you can export only records modified since the last run. The LastModifiedDate filter from the SOQL chapter does this.
#!/usr/bin/env bash
set -euo pipefail
ORG="my-prod-alias"
STATE="backup/last_run.txt"
SINCE="$(cat "$STATE" 2>/dev/null || echo 1970-01-01T00:00:00Z)"
NOW="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
DEST="backup/incremental/$(date +%Y%m%d-%H%M%S)"
mkdir -p "$DEST"
sf data query \
--query "SELECT Id, Name, Industry, LastModifiedDate FROM Account WHERE LastModifiedDate >= $SINCE AND LastModifiedDate < $NOW ORDER BY LastModifiedDate" \
--result-format csv \
--target-org "$ORG" > "$DEST/Account.csv"
echo "$NOW" > "$STATE"The script writes the new timestamp only after the query succeeds, because set -e ends the run earlier on failure. The upper bound < $NOW keeps a record that changes during the export from being missed in the next window.
An incremental export has limits you must plan for:
- It does not see deletions. A deleted record simply does not appear. Use the deleted-records approach from the earlier chapter, or run a periodic full export and compare Id lists.
- It produces change files, not a snapshot. To restore a point in time you must combine the baseline with later files, and keep the latest version of each Id.
- Some changes do not update
LastModifiedDateon the record you are exporting. Changing a child record may leave the parent untouched. Export every object you care about on its own.
Choosing a scheduler
| Scheduler | Good for | Watch out for |
|---|---|---|
| cron on a server | Simple nightly jobs on a machine you manage | The machine must be on, and cron has a minimal environment, so use absolute paths |
| CI job (scheduled pipeline) | Teams that already keep scripts in version control | Runners are often temporary, so upload the files before the job ends |
| Cloud scheduler with a container | No server to maintain | You must install the CLI in the image and supply secrets securely |
A cron entry that runs the script at 02:00 every day looks like this:
0 2 * * * /opt/backup/export.sh >> /var/log/sf-backup.log 2>&1Cron does not load your shell profile, so the sf command may not be on its PATH. Either set PATH at the top of the crontab or call the CLI with its full path inside the script.
Reporting failures
A job that fails quietly is worse than no job, because you believe you have a backup. Add at least one of these:
- Make the scheduler alert on a non-zero exit code. Most CI systems do this by default.
- Send a message at the end of a successful run, and alert when that message does not arrive. This catches the case where the scheduler itself stopped.
- Write the row counts to the log so you can see a sudden drop.
Limits that affect scheduled jobs
Each query counts against your org's daily API request allocation, and query results over a certain size need the Bulk API instead. The CLI's sf data query has a record cap, so large objects should use sf data export bulk or a Bulk API 2.0 query job, as covered in the earlier chapters on Bulk API and large volumes. Schedule the job outside business hours so that it does not compete with users and integrations for API capacity.
The whole routine fits together as follows.
Common errors
- Expired or revoked authorization. The job worked for weeks, then every run fails. Check the integration user, the certificate expiry date, and the connected app policies.
- Overwritten files. A fixed destination name replaces yesterday's backup. Always include a date or timestamp in the path.
- Local copies only. Files left on the machine that runs the job are lost together with that machine. Copy them to separate storage, as described in the chapter on protecting exported files.
- No retention. Daily folders grow without limit. Delete or archive old ones according to your retention policy.
- Time zone mistakes.
LastModifiedDatevalues are in UTC. Usedate -ufor the timestamps you compare against.
Exercise
An incremental export script queries WHERE LastModifiedDate >= $SINCE and then writes the current time to the state file. Name two ways a record can be missing from your backups, and one fix for each.
Show answer
First, a record deleted since the last run does not appear in any LastModifiedDate query. Fix it by also exporting deleted records or by running a periodic full export and comparing Ids. Second, if the script takes the "current time" after the query finishes, a record changed while the query ran can fall between windows. Fix it by capturing the time before the query, using it as an upper bound (LastModifiedDate < $NOW), and saving that same value as the next start.
Exercise
A nightly cron job ran for a month, then your team discovers the backup folder has had no new files for a week and nobody was alerted. Give two changes that would have caught this.
Show answer
Send a success message at the end of every run and alert when it is missing, which also catches a stopped server or scheduler. Make the script exit non-zero when a file has no rows, and have the scheduler alert on non-zero exit codes. Logging row counts and reviewing them would also show the problem.