Sub topic 3
Create a Scratch Org and Automate CLI Tasks
Assume you have basic terminal skills, an authenticated Dev Hub, and familiarity with Salesforce metadata, SOQL, and Apex. A scratch org is a temporary Salesforce org created from a definition file. The Dev Hub controls its creation and lifetime.
Create a scratch org
Create config/project-scratch-def.json:
{
"orgName": "Demo scratch org",
"edition": "Developer"
}Create the org, assign it an alias, and make it the default target:
sf org create scratch \
--definition-file config/project-scratch-def.json \
--alias myscratch \
--duration-days 7 \
--set-defaultThe alias is a short name that avoids repeatedly typing an org username. The default target is the org that commands use when you omit an explicit target.
Query records with SOQL
SOQL is Salesforce Object Query Language. Query records from the default target org:
sf data query \
--query "SELECT Id, Name FROM Account LIMIT 5"LIMIT restricts the number of returned records. Add --target-org myscratch when you want to make the target explicit.
Run Apex code and tests
Anonymous Apex is Apex code that runs without being saved as a class. Save this as hello.apex:
System.debug('Hello from the Salesforce CLI');Run it and then execute local Apex tests:
sf apex run --file hello.apex
sf apex run test --test-level RunLocalTests --result-format human --wait 10The --wait 10 flag waits up to ten minutes for test results.
Use JSON output in scripts
Many commands support --json. JSON is structured text that scripts can parse:
sf data query \
--query "SELECT Id, Name FROM Account LIMIT 5" \
--jsonFor example, a shell script can pass this output to a JSON parser such as jq.
Update the CLI and manage plugins
Update the Salesforce CLI and inspect installed plugins:
sf update
sf pluginsUse plugins only when you trust their source and understand the commands they add.
Exercise
How do you create a seven-day scratch org named testorg and make it the default target?
Show answer
Run sf org create scratch --definition-file config/project-scratch-def.json --alias testorg --duration-days 7 --set-default.