Close Sun May 26 21:16:34 GMT 2019

Running Apex code from Apache Ant

Almost every enterprise that automates Salesforce deployments will need to execute Apex code. For example:  test data set up in temporary environments, the assignment of permission sets, or the starting and stopping of scheduled jobs.

Apache Ant is a declarative cross-platform tool for defining build steps as XML. This Ant macro supports running Apex code from any build step using Execute Anonymous. It's self contained and doesn't require external java libraries.


First paste this macrodef into your build.xml

Then invoke the macro inside any build target:

<target name="execanon">
    <execanon username="${sf.username}" password="${sf.password}">
        System.debug('Stopping all scheduled jobs');
        for (SObject cron : [SELECT Id FROM CronTrigger])

How does it work?

First, the macro obtains a Session ID by logging into Salesforce using the username and password provided in the build properties file. Then it assembles the proper SOAP request to call ExecAnon using the Tooling API.

What if my code contains XML?

Add a <![CDATA[ ... ]]> section around the code. This will escape any < & > characters to entities before assembling the request body.

Benjamin Zomberg
I figured it out. This is how I was able to use a apex file for execution <target name="execanon"> <loadfile property="script" srcFile="${}"/> <execanon username="${sf.destination.username}" password="${sf.destination.password}" serverurl="${sf.destination.serverurl}" > ${script} </execanon> </target>
Benjamin Zomberg
I have apex files that I need to execute. Any way to ingest the contents of an apex file into this?
Matt and Neil
Fixed! The problem with certain Windows versions was caused by property expansion when the value contains backslashes. Script has been updated.
Deploy User
Hi! Great salotion! Could you help with this error?? no protocol: ${loginResponse.soapenv:Envelope.soapenv:Body.loginResponse.result.serverUrl}