How to execute Apex scripts using Ant

In some circumstances you might want to run Apex scripts as part of your deployment, for example to ensure data is anonymised in a pre-production environment.

This kind of scenario is often addressed as a manual post-deployment tasks, done either using Workbench or the Developer Console.

If you already use the Force.com Migration tool for deploying your changes, you might want this task to be also included in your script, for example after a successfully deployment, so that it's fully automated.

We will use ForceFlow, an open source project I started, that wraps methods from various Salesforce APIs, and exposes them as Ant tasks. ForceFlow includes a task named apex that allows to anonymously execute a script of Apex code.

Running a simple script

Let's assume we want to run a simple Apex script to anonymise all contact emails to avoid spamming during functional testing. The script would be something like this:

If you are already using the Force.com Migration tool to deploy changes, your project directory should have a structure that looks like this:

  • src/ - this directory contains your project metadata, we don't need to know the details
  • build/ - this directory contains the build scripts and resources
    • lib/ant-salesforce.jar - this is the Force.com migration tool
    • build.xml - this is the buildfile

This what you need to do:

  1. Get the latest release of ForceFlow from GitHub
  2. Unzip the archive and copy the jar file with dependencies in the same folder as your Force.com Migration tool (build/lib in our case)
  3. Amend your build.xml to include ForceFlow, as shown here.

You final buildfile should look like this.

Just launch ant deploy-and-anonymise to invoke the script.