Sub topic 9
Automating setup after a sandbox copy
This chapter assumes you can create and refresh sandboxes, as covered earlier in this tutorial. It also assumes you can read Apex and deploy metadata to production. Here you will learn how to make a fresh or refreshed sandbox ready to use without anyone repeating manual steps.
Why post-copy automation matters
A sandbox copy is a snapshot of production metadata, and for some sandbox types, data. After a copy or refresh, a team usually has a checklist of chores:
- Replace production endpoints with test endpoints.
- Create test users or adjust existing ones.
- Load a few records that every developer needs.
- Turn off integrations that should not run outside production.
Done by hand, this checklist is slow, easy to get wrong, and done differently by each person. It also grows into drift: one sandbox works and another does not, and nobody can say why.
Salesforce provides one hook for this: the SandboxPostCopy Apex interface. A class that implements it runs automatically after a sandbox is created or refreshed. The class is written once, tested, and attached to the sandbox, and every copy gets the same setup.
How the SandboxPostCopy interface works
The interface has one method, runApexClass(SandboxContext context). Salesforce calls it once, inside the new sandbox, when the copy finishes. The SandboxContext argument gives you three values:
| Method | Returns |
|---|---|
| `organizationId()` | The ID of the production org the sandbox was copied from |
| `sandboxId()` | The ID of the sandbox |
| `sandboxName()` | The name of the sandbox, such as `dev1` |
Several rules apply to the class:
- It must be declared
global, and so must therunApexClassmethod. - It needs a no-argument constructor. The default one is enough.
- It must exist in production, because the sandbox is a copy of production. Deploy it there before you create or refresh the sandbox.
- It runs in the sandbox, so DML and queries affect the sandbox only.
- It runs once, with ordinary Apex governor limits. Heavy work needs to be split into asynchronous jobs.
The script runs on the user's behalf and with that user's permissions. Check Salesforce's documentation for the exact running-user behavior in your release before you rely on it for permission-sensitive work.
Writing a post-copy class
The class in the topic example logs where the sandbox came from. A useful version also does some work. The following version seeds three accounts, and it is safe to run more than once. Idempotent means that a second run leaves the same result as the first. Refreshing a sandbox should never produce duplicates.
global class PrepareSandbox implements SandboxPostCopy {
global void runApexClass(SandboxContext context) {
System.debug('Sandbox ' + context.sandboxName() + ' (' + context.sandboxId()
+ ') copied from org ' + context.organizationId());
seedAccounts(context.sandboxName());
}
private void seedAccounts(String sandboxName) {
Integer existing = [SELECT COUNT() FROM Account WHERE Name LIKE 'Sandbox Seed%'];
if (existing > 0) {
return;
}
List<Account> seeds = new List<Account>();
for (Integer i = 1; i <= 3; i++) {
seeds.add(new Account(
Name = 'Sandbox Seed ' + i + ' (' + sandboxName + ')',
Description = 'Created by PrepareSandbox after copy'
));
}
insert seeds;
}
}The SELECT COUNT() check is the idempotency guard. Without it, a Full or Partial Copy sandbox that already carries a seed record would receive duplicates.
Testing the class
Salesforce requires 75% Apex test coverage to deploy to production, and the post-copy class has to be deployed there. Write a test. The platform gives you Test.testSandboxPostCopyScript to run the class the way Salesforce would.
@IsTest
private class PrepareSandboxTest {
@IsTest
static void seedsAccountsOnce() {
Id orgId = UserInfo.getOrganizationId();
Test.startTest();
Test.testSandboxPostCopyScript(new PrepareSandbox(), orgId, orgId, 'dev1');
Test.testSandboxPostCopyScript(new PrepareSandbox(), orgId, orgId, 'dev1');
Test.stopTest();
System.assertEquals(3, [SELECT COUNT() FROM Account WHERE Name LIKE 'Sandbox Seed%'],
'Running the script twice should still leave exactly three seed accounts');
}
}Running the script twice in the test proves that the guard works. That is the case most likely to break after a real refresh.
Attaching the class to a sandbox
There are two ways to tell Salesforce which class to run.
In Setup, the sandbox creation and refresh wizards have a field for the Apex class to run after the copy. Pick PrepareSandbox there.
With the CLI, put the class ID in the sandbox definition file. The topic's earlier example defined only the name and license type. Add the apexClassId property:
{
"sandboxName": "dev1",
"licenseType": "Developer",
"apexClassId": "01pXXXXXXXXXXXXXXX"
}Replace the placeholder with the real ID of the class in production. You can look it up with the CLI:
sf data query --query "SELECT Id FROM ApexClass WHERE Name = 'PrepareSandbox'" --target-org prodThen create the sandbox as before:
sf org create sandbox --definition-file config/dev-sandbox-def.json --alias dev1 --target-org prodWhen you refresh a sandbox, you choose the class again. Do not assume the previous choice carries over without checking the refresh screen.
What to automate
Not every chore belongs in the script. Use the table to decide.
| Task | Good fit for post-copy? | Notes |
|---|---|---|
| Insert seed records | Yes | Keep the volume small and guard against duplicates |
| Change custom settings or custom object values | Yes | Plain DML works |
| Update endpoints in custom settings | Yes | Replace production URLs with test URLs |
| Abort scheduled jobs that talk to external systems | Yes | Query `CronTrigger` and call `System.abortJob` |
| Change custom metadata type records | Partly | DML does not work on them. Use `Metadata.Operations.enqueueDeployment` |
| Load thousands of records | No | Use a data-loading tool or a Queueable job started from the script |
| Mask sensitive production data | Not alone | Use a dedicated masking tool. See the chapter on test data and data protection |
| Assign permission sets to users | Yes, with care | See the mixed DML warning below |
Common problems
Mixed DML errors
Salesforce does not allow DML on setup objects (such as PermissionSetAssignment or User) and non-setup objects (such as Account) in the same transaction. A post-copy script that seeds accounts and also assigns permission sets can fail with MIXED_DML_OPERATION. Split the work. Run the setup-object DML in a separate transaction, for example in a Queueable class that the script enqueues with System.enqueueJob. You can also run it inside System.runAs in test context, but that approach only helps tests, not the real script.
Failures are quiet
A script that throws an exception does not stop the sandbox from being created. The sandbox appears and looks normal, but your setup did not complete. Salesforce notifies the user who ran the create or refresh, but people miss those emails. Defend against this:
- Wrap risky steps in
tryandcatch, and keep going after a failure. - Write a record or a debug log that says which steps ran.
- After each refresh, check one known effect, such as the seed accounts, before announcing the sandbox is ready.
Limits apply to the script
The script runs in a single transaction, so the usual limits apply: 150 DML statements, 100 SOQL queries, and 10,000 DML rows. If you bump into them, move the bulk work into asynchronous Apex.
The class depends on data that may not exist
Developer and Developer Pro sandboxes copy metadata only. Partial Copy sandboxes copy a sample of data, and Full sandboxes copy everything. A script that assumes a certain account exists will work in a Full sandbox and fail in a Developer sandbox. Query for what you need and handle the empty result.
Keeping the script maintainable
Treat PrepareSandbox like any other production code:
- Store it in your Git repository with the rest of the project source, so changes go through review.
- Keep each step in its own private method with a clear name, such as
seedAccountsorabortExternalJobs, so the run order is easy to read. - Make every step idempotent, because refresh runs will repeat it.
- Keep an updated list of what the script does next to your sandbox definition files, so new team members know what to expect in a fresh sandbox.
Scratch orgs do not use this interface. They have no copy step, because you build them from a definition file and project source. Their equivalent is a setup script in your CI or developer workflow, which runs sf commands after org creation. The sandbox hook is for orgs that are copied from production.
Exercise
A team refreshes their Developer Pro sandbox every two weeks. Their PrepareSandbox class inserts three seed accounts, but after the third refresh developers report nine duplicate seed accounts. What went wrong, and how do you fix it without removing the seed step?
Show answer
The script is not idempotent. It inserts the seed records on every run, and the earlier seed accounts survive each refresh, so they accumulate (for example if the data is carried in the copy or if the script ran more than once). Add a guard at the start of the seeding step, such as a SELECT COUNT() on accounts whose name starts with the seed prefix, and return without inserting if any exist. Then extend the test class to call Test.testSandboxPostCopyScript twice and assert that exactly three seed accounts exist.
Exercise
You add a post-copy class directly in a sandbox named dev1 and test it there. After the next refresh of dev1 from production, the class is gone. Why, and what should you do?
Show answer
A refresh replaces the sandbox contents with a fresh copy of production, so anything that exists only in the sandbox is lost. The post-copy class must be deployed to production, and its test must pass there, before you create or refresh the sandbox. Keep the class in version control, deploy it to production through your normal pipeline, and select it in the refresh wizard or through apexClassId in the sandbox definition file.