Complete Salesforce Deployment Guide using Ant Migration Tool

Step by Step tutorial of Salesforce Migration using ANT tool with Proxy settings and retrieving content from Salesforce Organization. Also fix some common errors like java.lang.OutOfMemoryError or unable to find tools.jar

Following are the many tools available for Salesforce deployment like

  1. Change sets (From Salesforce site)
  2. Eclipse (Using “Deploy to force.com server” option in Eclipse)
  3. ANT (Java based tool)

We are going to discuss the ANT based migration, step by step:

Prerequisite:
JDK 1.5 or above

Step 1:
Download ANT distribution from – “http://ant.apache.org/bindownload.cgi

Step 2:
Set Environment variable “ANT_HOME“. The path should be of parent folder of “bin”. Also add the “bin” folder to your path.

Step 3:
Check whether ANT is installed or not properly by running command “ant -version“. It might be possible that you receive message something like unable to find tools.jar. You can copy this jar from “JDK_HOME/lib/tools.jar” to “JRE/lib” folder.

Salesforce Get ANT version
Salesforce Get ANT version

In above screen you can see that before copying tools.jar I was getting warning.

Step 4:

Login to salesforce and navigate to “Your Name |Setup | Develop | Tools” and download “Force.com Migration tool”.

Unzip the downloaded file to the directory of your choice. Copy the “ant-salesforce.jar” file from the unzipped file into the ant lib directory.

To start with deployment using ANT, we will need “build.xml” and “build.properties” file. As there is no need of “build.properties” however its good to have it so that the configuration related settings are in different file. You can copy both files from “sample” folder of unzipped content from salesforce. Following is the structure of “build.properties” file.

# build.properties
# Specify the login credentials for the desired Salesforce organization
sf.username = <SFDCUserName>
sf.password = <SFDCPasswrd>
#sf.pkgName = <Insert comma separated package names to be retrieved>
#sf.zipFile = <Insert path of the zipfile to be retrieved>
#sf.metadataType = <Insert metadata type name for which listMetadata or bulkRetrieve operations are to be performed>
# Use 'https://login.salesforce.com' for production or developer edition (the default if not specified).
# Use 'https://test.salesforce.com for sandbox.
sf.serverurl = https://test.salesforce.com

Step 5:
Copy all folders with source code from source organization using eclipse. Lets say the root folder name is “test1”.
Create “build.properties” from above code snippet or copy it from unzipped folder. Now create “build.xml” needed by ANT. Following is the example of build.xml file:

<project name="Shivasoft ANT Tutorial" default="deployCode" basedir="." xmlns:sf="antlib:com.salesforce">
    <property file="build.properties"/>
    <property environment="env"/>
    <!-- Shows deploying code &amp; running tests for code in directory -->
    <target name="deployCode" depends="proxy">
      <sf:deploy username="${sf.username}" password="${sf.password}" serverurl="${sf.serverurl}" deployRoot="test1">
        <runTest>TestClassName</runTest>
      </sf:deploy>
    </target>
    <!-- Shows removing code; only succeeds if done after deployCode -->
    <target name="undeployCode">
      <sf:deploy username="${sf.username}" password="${sf.password}" serverurl="${sf.serverurl}" deployRoot="removecodepkg"/>
    </target>
	<target name="proxy">
		<property name="proxy.host" value=" ProxyURL " />
		<property name="proxy.port" value="1234" />
		<property name="proxy.user" value="UserName" />
		<property name="proxy.pwd" value="Password" />
		<setproxy proxyhost="${proxy.host}" proxyport="${proxy.port}" proxyuser="${proxy.user}" proxypassword="${proxy.pwd}" />
	</target>
</project>

Attribute “deployRoot” means the root folder from which the code should be copied and tag <runTest> means the testclasses which should run after the deployment. At last, go to the folder “test1” from command line and run command “ant deployCode”.

 

Salesforce Migration using-ANT
Salesforce Migration using-ANT

Checking the status of the task:
To know the status of task you can run command:
Ant targetName -Dsf.asyncRequestId=requestID

Using Proxy in ANT migration tool:
If your organization uses the proxy then add below target in “build.xml” and specify this target as dependent.

<target name="proxy">
		<property name="proxy.host" value=" ProxyURL " />
		<property name="proxy.port" value="1234" />
		<property name="proxy.user" value="UserName" />
		<property name="proxy.pwd" value="Password" />
		<setproxy proxyhost="${proxy.host}" proxyport="${proxy.port}" proxyuser="${proxy.user}" proxypassword="${proxy.pwd}" />
	</target>

Retrieve content from Salesforce Organization:
create “package.xml” for the list of component to be retrieved and add following task in “build.xml”.

<!-- Retrieve an unpackaged set of metadata from your org -->
<!-- The file unpackaged/package.xml lists what is to be retrieved -->
<target name="test" depends="proxy">
  <mkdir dir="retrieveUnpackaged"/>
  <!-- Retrieve the contents into another directory -->
  <sf:retrieve username="${sf.username}" password="${sf.password}" serverurl="${sf.serverurl}" retrieveTarget="retrieveUnpackaged" unpackaged="unpackaged/package.xml" unzip="false" />
</target>

“Unzip” attribute specifies that the code retrieved should be in Zip format or not. By default the value is true means it will not in zip format.

Delete components from Salesforce Organization using “destructiveChanges.xml” :
In some cases, we may want to delete some components like Object or fields from Salesforce Organization. In this case, Only “package.xml” will not work. We need to create “destructiveChanges.xml” file also. Syntax for this file is exactly same as of “package.xml”, except that here we cannot define wildcards. So, to undeploy anything from Salesforce org, we need two xml files – “package.xml” and “destructiveChanges.xml“.

Below is complete code of build.xml, which includes retrieve, Undeploy and Deploy commands.

<project name="Shivasoft Demo Org" default="deployCode" basedir="." xmlns:sf="antlib:com.salesforce">
	<!-- Get all settings like Server Path, username and passwords from "build.properties" file -->
    <property file="build.properties"/>
    <property environment="env"/>
	<!-- Sequence 1 - Get All information from Source, Retrieve the contents into Src directory -->
	<target name="SFDCFetch">
	  <!-- -->
	  <sf:retrieve username="${sf.username}" password="${sf.password}" serverurl="${sf.serverurl}" retrieveTarget="src" unpackaged="package.xml"/>
	</target>

	<!-- Sequence 3 - Deploy to Target System, Package.xml is present in Src folder -->
	<target name="deploy">
      <sf:deploy username="${sf1.username}" password="${sf1.password}" serverurl="${sf.serverurl}" deployroot="Src">
      </sf:deploy>
    </target> 

	<!-- Sequence 2 - If you want to remove some components, destructiveChanges.xml and Package.xml present in Delete Folder -->
	<target name="unDeploy">
      <sf:deploy username="${sf1.username}" password="${sf1.password}" serverurl="${sf.serverurl}" deployroot="Delete">
      </sf:deploy>
    </target>
</project>

You may also be interested to check how to automate daily Salesforce backup.

Update [03-Apr-2017]

Question : Why Salesforce ANT Migration tool is giving wrong Username, Security token or password error, even when everything is correct ?
Ans : If your password contains “$”, then ANT tool ignores this characters. So, to correct this, we need to add one more “$”.

Question : Why I am getting error like java.lang.OutOfMemoryError: Java heap space while retrieving metadata from Salesforce. 

Ans : It is possible that you are retrieving metadata of some big organization with lots of changes. In this case, Java JVM running on system needs more memory (RAM) in order to process it. It can be done in two ways

1. Before running ANT command, run below command which will set the RAM allocated for JVM to 1GB. If you are not a Windows user, then use export instead of set in below command.

set ANT_OPTS=-Xmx1g

2. Problem in above solution is that, you would need to execute set command every time before using ANT. For permanent solution, open ant.bat file in bin folder of ANT installation (Same installation folder referred in ANT_HOME). And, at very first line, write below command and save it.

set ANT_OPTS=-Xmx1g

I hope this article will help newbie to learn ant migration tool.

Related posts

  • Sunu

    Thank you very much for the post

  • Vinay

    Thanks a lot, very informative.

  • sra

    Very good thanks shiva

  • How can I deploy a folder using ant tool:

    when I used the below codes to deploy the folder :

    EMEA_Pricing_Approval_Templates
    Folder

    It gives the error:
    Retrive Commands ::

    F:AntDemosample>ant retrieveUnpackaged
    Buildfile: F:AntDemosamplebuild.xml
    retrieveUnpackaged:
    [sf:retrieve] Request for a retrieve submitted successfully.
    [sf:retrieve] Request Id for the current retrieve task: 04s900000025E2EAAU
    [sf:retrieve] Waiting for server to finish processing the request…
    [sf:retrieve] Request Status: Completed
    [sf:retrieve] Retrieve warnings (1):
    [sf:retrieve] package.xml – Entity type: ‘Folder’ is unknown
    [sf:retrieve] Finished request 04s900000025E2EAAU successfully.

    Deploy command::

    F:AntDemosample>ant deployUnpackaged
    Buildfile: F:AntDemosamplebuild.xml
    deployUnpackaged:
    [sf:deploy] Request for a deploy submitted successfully.
    [sf:deploy] Request Id for the current deploy task: 04s90000002BZDxAAO
    [sf:deploy] Waiting for server to finish processing the request…
    [sf:deploy] Request Status: Completed
    BUILD FAILED
    F:AntDemosamplebuild.xml:37: FAILURES:
    Error: package.xml():Unknown type name ‘Folder’ specified in package.xml
    Total time: 16 seconds

    Any help will be appreciated..:)

  • Dedo

    Nice tutorial 🙂 can I run ANT to retrieve and deploy from/to salesforce from Eclipse?

    • JitendraZaa

      Eclipse already have inbuilt Migration tool.

  • planecrash

    How do I do a site to site copy? I get errors if I select every object in the eclipse dialog. For instance case assignments object for users in one site and not another?

    • planecrash

      Eventually figured it all out, was a pain in the butt!

      • JitendraZaa

        I just checked ur comment.. What was wrong at ur side ? If u can suggest i will update this article. Your feedback is appreciated

        • planecrash

          Well basically I was given access to a development instance a consultant had coded. My level of experience was low, and it was difficult determining which metadata components to select, without any input from the people who wrote it, to completely move the custom app from one instance of salesforce to another. I have since identified the list of metadata components required in the migration and have continuous integration up and running with ant, the migration tool, Git, and JetBrains’ TeamCity.

  • Salesforce user

    Thanks, it helped me in setting up proxy in build.xml

  • Ta

    Hi I want to read a xml file form my local machine and update the account object with the xml data using ANT…please suggest me how should I achieve it.

  • Pingback: Ant migration tool–FAILED TO SEND REQUEST | DL-UAT()

  • Hardik Chavda

    Hi Sir, I read your post. I have to say excellent job. I have one doubt though. If we can migrate everything using eclipse then why do we need ANT migration tool, In short my question is, What is it in ANT that makes it different from eclipse migration process? And what are the components that we can migrate using ANT but not using Eclipse.

  • Skender Kollcaku

    Hi,

    First of all thanks for this guide.
    I get the following error and sincerely do not fully understand what is the deployRoot:

    ./ant deployPlivoCheckOnly
    Buildfile: C:Antapache-ant-1.9.6-binapache-ant-1.9.6binbuild.xml
    deployPlivoCheckOnly:

    [echo] Run ‘ant deployPlivo’ to deploy this library to your organization.
    [echo] Testing deployment of Plivo Helper Library for Salesforce without saving changes…
    BUILD FAILED
    C:Antapache-ant-1.9.6-binapache-ant-1.9.6binbuild.xml:22: Should provide a valid directory ‘deployRoot’ or a zip file ‘zipFile’.

    Any suggestion?

    Thanks,
    Skender

    • Not very sure but seems you have created build.xml in bin folder of ANT itself. I would suggest, remove ANT and fresh install. Set Class path for ANT bin folder and set ANT_HOME environment variable. create isolated folder for your project and run ANT from there.

      • Skender Kollcaku

        Hi, You are right.

        I did it from the start and now it should be all fine:

        C:Plivoplivo-salesforce-masterinstall>ant deployPlivo

        Buildfile: C:Plivoplivo-salesforce-masterinstallbuild.xml

        deployPlivo:

        [echo] Deploying Plivo Helper Library for Salesforce…
        [sf:deploy] Request for a deploy submitted successfully.
        [sf:deploy] Request ID for the current deploy task: 0Af58000002UomDCAS
        [sf:deploy] Waiting for server to finish processing the request…
        [sf:deploy] Request Status: InProgress
        [sf:deploy] Request Status: Succeeded
        [sf:deploy] *********** DEPLOYMENT SUCCEEDED ***********
        [sf:deploy] Finished request 0Af58000002UomDCAS successfully.

        BUILD SUCCESSFUL

        Total time: 15 seconds

        Now my question is: what is the next step in the integration process?
        How do I see a sample Demo Plivo app in my Salesforce instance?

        Thanks again,
        Skender

  • Harihar Tiple