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.

Usage:

First paste this macrodef into your build.xml

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

Then invoke the macro inside any build target:

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.

Related Posts

Last modified: 4th August 2019

Comments

Ramon Loureiro 

Hi!
Great solution!
Could you help with this error??
java.net.MalformedURLException: no protocol: ${loginResponse.soapenv:Envelope.soapenv:Body.loginResponse.result.serverUrl}

    Thank you – this is now fixed in the updated script. The problem with Windows versions was caused by property expansion when the value contains backslashes.

Benjamin Zomberg 

I have apex files that I need to execute. Any way to ingest the contents of an apex file into this?

    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="${sf.script.name}"/>
        <execanon username="${sf.username}" password="${sf.password}" serverurl="${sf.serverurl}">
            ${script}
        </execanon>
    </target>
    

Write a Reply or Comment

Your email address will not be published.