Sub topic 9
Automating setup after a sandbox copy
This chapter assumes you can create a sandbox and know that a refresh replaces its contents with a fresh copy of the source org. It also assumes you can write basic Apex. Here you will automate the setup work that would otherwise be repeated by hand after every refresh.
Why automate post-copy setup
A new or refreshed sandbox starts as a copy of its source org. Anything you changed in the old sandbox is gone. That includes test records, adjusted settings, and masked data. If an admin redoes these steps by hand, steps get skipped and sandboxes drift apart.
Salesforce lets you attach an Apex class to the sandbox. It runs once, automatically, after the copy finishes.
The SandboxPostCopy interface
Your class must implement SandboxPostCopy. This interface has one method, runApexClass. The method receives a SandboxContext object with three read-only values:
| Method | Returns |
|---|---|
| `organizationId()` | The ID of the org the sandbox was copied from |
| `sandboxId()` | The ID of the new sandbox |
| `sandboxName()` | The sandbox name, for example `dev1` |
The class and method must be global. You can use the context values to behave differently per sandbox, such as seeding more data in a QA sandbox than in a developer sandbox.
A working example
The class below seeds one Account and starts a batch job that masks Contact email addresses. A batch job is used because a sandbox can hold far more Contacts than a single transaction can update.
global class PrepareSandbox implements SandboxPostCopy {
global void runApexClass(SandboxContext context) {
System.debug('Preparing ' + context.sandboxName()
+ ' (' + context.sandboxId() + ') copied from org '
+ context.organizationId());
insert new Account(Name = 'Sandbox Smoke Test Account');
Database.executeBatch(new MaskContactEmails(), 200);
}
}global class MaskContactEmails implements Database.Batchable<SObject> {
global Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator(
'SELECT Id, Email FROM Contact WHERE Email != null');
}
global void execute(Database.BatchableContext bc, List<Contact> scope) {
for (Contact c : scope) {
c.Email = c.Email.replace('@', '=') + '@example.invalid';
}
update scope;
}
global void finish(Database.BatchableContext bc) {}
}An address like [email protected] becomes [email protected]. It is still a valid email format, but mail cannot reach a real person.
Attaching the class
Follow these steps to attach the class to a sandbox:
- Deploy both classes to the source org, usually production. The sandbox is a copy of that org, so the class must exist there before you create or refresh the sandbox.
- Make sure the classes meet the test coverage required for production deployment.
- Choose the class when you create or refresh the sandbox. In Setup, the sandbox creation and refresh pages have an Apex class field.
Common errors
- Class not found in the list. It was not deployed to the source org before the sandbox was created. Deploy it, then refresh.
- Governor limit errors. The class runs in a normal Apex context. Move large updates into batch or queueable jobs, as the example does.
- Silent failure. A failure in your class does not stop the sandbox from being created, so the sandbox may look fine but be unprepared. Wrap risky steps in
try/catch, log failures, and check Apex Jobs after each refresh. - Not idempotent. The class runs on every refresh. Write it so repeated runs do not break anything.
- Hard-coded IDs. Record IDs differ between orgs. Query by name or another stable field.
Exercise
You added a SandboxPostCopy class to production today. Your existing sandbox dev1 was refreshed yesterday. Why did the class not run, and what must you do for it to run?
Show answer
The class runs only when a sandbox is created or refreshed, and dev1 was copied before the class existed in production. Refresh dev1 (or create a new sandbox) and select the class on the refresh page. The class must already be deployed to the source org.