Skip to main content

Running anonymous Apex scripts as a post-deployment step in Pipelines

Run an anonymous Apex script automatically as a post-deployment step on a PR in Pipelines.

Written by Jacob Joshua

License requirements: Anonymous Apex steps in Pipelines are available on Automation license tiers.

Gearset can run an anonymous Apex script for you as a post-deployment step in Pipelines. You attach the script to a PR, choose the environments it runs in, and Gearset executes it after the PR deploys successfully to each of those environments.

Use it for jobs you'd otherwise run by hand after a deployment, such as updating records or reassigning cases.

How do I turn on anonymous Apex for my team?

Anonymous Apex is off by default. A team Owner turns it on in Pipeline settings, under Deployment Steps. The setting applies to the whole team, not to individual users.

Warning: There's no rollback for anonymous Apex, and Gearset doesn't review what a script does. Gearset posts each script as a comment on the PR, but the comment doesn't block the PR or reset approvals. Make sure each script is reviewed and correct before you promote the PR.

Scripts run automatically after deployment, so turn it on only when your team is happy with how scripts get reviewed.

  1. Open your pipeline and go to settings. (Put correct path)

  2. Turn on (Put correct screenshot or step here).

[Screenshot: Anonymous Apex toggle in Pipeline settings]

How do I add a script once it's on?

Once the setting is on, Anonymous Apex appears as a post-deployment step type on your PRs.

You can run each script in all environments or only in the ones you choose.

When you add the step while creating the PR in Pipelines, set Run against to specific environments only and pick any environments, such as production only. The step will be added to the PR as a comment.

If you add the step later, or the PR was created outside Pipelines (for example, from Compare and Deploy), the environment the PR is currently in is always included, though you can add later environments too. Steps set to All environments are also copied onto back-propagation PRs, so the script runs again in lower environments.

To add a script to a PR, see Adding an automatic post-deployment step.

If a script fails, Gearset doesn't retry it. The step shows We couldn't complete this automatic step. and appears in the environment's Pending completion tab. Run the script manually, then tick Mark anonymous Apex as complete, as described in Managing your pre/post-deployment steps.

To see each script and its output, open the pipeline sidebar, go to Promotion history, click View all promotion history, and open the Deployment steps tab.

Note: The script runs as the user on your CI job's org connection. That user needs both the Author Apex and API Enabled permissions in Salesforce.

Did this answer your question?