The Wayback Machine - https://web.archive.org/web/20180420121251/http://php.sys-con.com:80/node/43787

Welcome!

PHP Authors: Liz McMillan, Carmen Gonzalez, Hovhannes Avoyan, Lori MacVittie, Trevor Parsons

Related Topics: Apache, ColdFusion, PHP, Ruby-On-Rails, Perl, Python

Apache: Article

An Introduction to Ant

Automate and improve your build and deploy process

Writing shell scripts to automate the build and deploy process for ColdFusion applications is not very much fun. The Jakarta Ant project is an open-source, cross-platform alternative that makes it easy to automate the build and deploy process.

But My Build and Deploy Process is Fine....
Maybe your build and deploy process for your latest application is fine - you type a single command and your build process automatically retrieves your application from the source control system, configures the application appropriately for the target environment, and copies all the necessary files to the production servers while you head to the coffee shop for your morning cup of caffeine and the newspaper. But I know that the reality for the vast majority of projects I've seen (including many of my own applications!) are built and deployed using a written multistep checklist - some steps automated by simple shell scripts and some done by hand. With time a scarce commodity on most projects, it's not a surprise that anything other than the ColdFusion application itself gets little, if any, attention.

But how many times have you personally been burned by a bad build or deploy? Maybe forgetting to copy a custom tag to the \CFusionMX\CustomTags directory? Or deploying the wrong version of a ColdFusion template? Maybe you forgot to toggle the data source name from the development server to the production server? Or neglected to disable some debugging code? The list goes on. How much time did you waste finding and fixing the problem? Odds are it was a lot, and that the problem happened at the least opportune time, like during a major production release! If there was a simple, free, cross-platform, extensible tool that would let you write automated build and deploy scripts, wouldn't it make sense to use it?

There are some traditional tools for automating builds: the venerable make is familiar to anyone who's done much work on Linux or with C applications; jam may be familiar to some hard-core open-source developers; and native shells on Windows (DOS and third-party replacements including cygwin) and Unix (bash, csh, zsh, and their relatives) can all be used. But anyone who has used make or its derivatives can relate to the frustrations of accidentally putting a space in front of a tab and trying to figure out why the script is not working. And shell scripts are both platform specific and can be very limited in their capabilities (particularly the DOS shell).

One Java programmer, James Duncan Davidson, became so frustrated with the existing build tools while he was creating Tomcat (the official reference implementation for Java Servlets and JavaServer Pages) that he wrote his own build tool, which he dubbed Another Neat Tool (Ant). The Ant tool itself is implemented in Java, which allows it to run consistently across most modern operating systems, and also makes it easy to extend so that it can do any tasks that Java can (more on that later). Ant-built scripts are written in XML, which makes them much easier to write (and validate!). Ant rapidly expanded into a number of Apache Jakarta projects and from there to the many Java developers who downloaded the Jakarta tools. Today, Ant is a de facto standard tool for automating many aspects of the Java software development process. Instead of the "make install" of the C world, Java developers now have "ant deploy"!

So why should you, as a ColdFusion developer, be interested in Ant? If your ColdFusion applications deploy seamlessly to Linux and Windows servers with a single command, then you might not need Ant, but otherwise it's going to become a key tool in your software development toolbox. More important, now that ColdFusion MX is so tightly coupled to the Java world, using Java tools simply makes sense. Even the ColdFusion MX updaters use Ant scripts for part of the upgrade process!

Installing Ant
The Apache Ant project home page http://ant.apache.org/ provides both source and binary distributions of Ant, as well as the manual, links to key resources, and even a Wiki. For most purposes, the binary distribution for your platform should be sufficient, especially if you're new to Ant. The latest Ant release, 1.6.0, debuted in mid-December of 2003, though there's nothing wrong with Ant 1.5.x should that version already be available in your environment. And since Ant is a Java application, you'll also need an installed JDK, version 1.2 or later - the latest Sun JDK 1.4 is available from http://java.sun.com/j2se/1.4.2/download.html.

Installing the Ant binaries is simply a matter of unzipping the archive into a directory on your computer and completing two configuration steps:

  1. The Ant\bin directory needs to be added to your path.
  2. Add the environment variable ANT_HOME, and have it point to the installation directory.

    There is also an additional, optional, step:

  3. Add the environment variable JAVA_HOME, which points to the installed JDK directory.

So on a Windows 2000/XP computer, the configuration might look like Listing 1. There are bash and csh equivalents for Unix in the Ant reference manual (http://ant.apache.org/manual/index.html).

You can test your installation by opening a console window and typing

ant -version

which should produce a version number and compile date for your Ant installation.

Using Ant
Now that you've got Ant installed, what's the next step? Why, a build file of course! You're going to need a console window and your favorite text (or XML) editor to get started. The Ant command expects a buildfile (which defaults to build.xml) that contains an XML description of build targets, which are steps in the build process. And each target consists of one or more tasks that need to occur. Listing 2 contains a very simple buildfile. If you save Listing 2 as build.xml and simply type "ant", you'll get something that looks like this:

Buildfile: build.xml
help:
[echo] usage: ant [target]
[echo] typical targets: init, dist, deploy, help
BUILD SUCCESSFUL
Total time: 4 seconds

It's worth noting that since we didn't pass in any particular target, Ant used the default target name defined in the <project> tag. Typing "ant help" will produce the same output. In this buildfile, we've got a single <target> that has two <echo> tasks. The <echo> task simply writes text to the screen.

Now that we've got the Ant equivalent of a "Hello World" application, let's get down to the business of creating the build process for a real ColdFusion application using Ant. To get started all we need to do is retrieve the source code from the source code control repository (I'm going to use Microsoft Visual SourceSafe for this example) and prepare it for deployment. I'm going to use the following Ant targets for our build process:

  1. init: Create the directories for the project
  2. getSource: Pull the latest source code from the repository
  3. build: Process the source code to prepare it for the deployment environment
  4. dist: Package the source for distribution/deployment
  5. deploy: Copy the distribution package to the production server
  6. clean: Remove all files and directories associated with the project

The entire buildfile is shown in Listing 3, and it's certainly expanded a lot!

Putting Our Buildfile Under the Magnifying Glass
There are a lot of new things to absorb in this buildfile and we have limited space, so we're going to look at each target individually in the following section and go over the major points. If you want details on any of the specific tasks (or any of the dozens of other Ant tasks) you might want to peruse the Ant online manual (http://ant.apache.org/manual/index.html) as you read along.

The init target shouldn't be too hard to interpret - it uses the <mkdir> task to create three directories: src, build, and dist. This task will create each of these three directories if they don't already exist. As an aside, these specific directory names have become conventional on Ant projects. Type "ant init" and the three directories will be created to hold your application. Since the <mkdir> in our buildfile is using relative paths, the directories will be created underneath the directory where the buildfile is located.

The clean target looks very similar to the init target, with the <delete> task replacing the <mkdir>. As you probably intuited, we're simply deleting the directories we created with the init. But one new feature is the depends attribute in the <target> tag. The depends attribute can be used to describe dependencies between targets. In this case, the buildfile is indicating that the clean target can run only after the init target has been run, so Ant automatically runs init for you, but only if the target needs to be run! You can test this by running the clean target two or more times - if the directories exist (and thus the init dependency is satisfied), the clean tasks simply deletes them, but if the directories do not exist, Ant runs the dependent init target to create them and then deletes them. Try it and watch the output!

The getsource target is where things really get interesting. We want to get the source code out of our Microsoft Visual SourceSafe (VSS) repository so we can build and deploy it. Ant has built-in tasks for manipulating all of the major (and many minor) source control applications. (As an aside, there are actually eight Ant tasks for manipulating VSS; these and all of the other vendor-specific tasks are listed in the "Optional Tasks" section of the Ant manual.) In this example, we're using <vssget> to pull code from the VSS. The buildfile is passing in a number of VSS-specific parameters which result in the latest source code being pulled from the repository and put into the \src directory. Note that this target also depends on the init target, since the \src directory needs to exist before we start getting the source code.

The build target is pretty simple in this buildfile - it uses the <copy> task to copy all of the files in the \src directory to the \build directory. The <copy> task is interesting because it uses an Ant type, the <fileset>. There are over a dozen Ant types, which represent complex data structures that Ant natively understands. In this case we're defining a set of files with the <fileset> type, which is then used by the <copy> task.

The build target depends on the getsource task, since we need source code before we can copy it to another directory, since getsource depends on init, we've now used the depends attribute to chain three targets together in the proper order, which you can verify by running the build target and watching the dependent tasks execute in the Ant output.

The dist target is exactly like the build target, simply copying files from one directory to another. If we were using Ant for a Java application, this is the step where the compiled class files would be packaged into a JAR file for distribution. So the net result of all of these steps so far is to pull out the source code from VSS, copy it to the \build directory, and then copy it to the \dist directory. We could have skipped the build and dist targets, but we'll talk more about why they're useful in the final section of this article.

Finally, we've got the deploy target, which in this case is copying the files in the \dist directory to another directory, perhaps a network share to the integration or production server. We're using the <mkdir> and <copy> tasks again, but this time the directory name looks a little weird. One powerful concept in Ant is the "property". In this example, the deploy target expects a property called "deploy.dir", which represents the directory the \dist directory should be deployed to. The syntax for a property is ${varname}. Properties can be configured a number of ways using the <property> task, ranging from assigning it directly in the buildfile to using environment variables or the command line. Let's assume for a minute that I can deploy the files to two directories, c:\apache2\htdocs\test for my local test Web server, and l:\apache2\htdocs\production for the production Web server. The property can be input from the command line using the -Dproperty=value syntax, like the following example

ant deploy -Ddeploy.dir=c:\\apache2\\htdocs\\test

Note that there is no space between the -D option and the property=value information. And since I'm running on a Windows machine, I do have to remember to escape the backslash just like I would have to in a Java .properties file. But the buildfile doesn't know anything about Windows, Linux, Mac, or anything else, so you can deploy to /var/httpd/htdocs/test just as easily.

Next Steps
The first step I'd recommend taking is to automate your build process using Ant if you don't already have a solution. Now. Right now. Go! And if you do have a build process in place, I'd suggest taking a hard look at whether it's worth moving to Ant for its simplicity (relatively speaking), extensibility, and cross-platform support. We've literally just scratched the surface of Ant, but this buildfile is already useful and a great starting point for experimentation (and maybe another article? Let me know!). Just some quick tidbits to whet your appetite for more Ant:

  • Use <filter>s to replace tokens in files with new values, maybe to toggle debugging flags and set datasource names that vary between deployment environments.
  • Schedule Ant using cron, at, Windows scheduler, or the like for nightly builds, and send e-mail to the team about the results.
  • Integrate automated testing tools (JUnit, HTTPUnit, etc) into the build.
  • Deploy using FTP, telnet, or other methods to a remote server.
  • Write your own Ant tasks that extend existing tasks or implement new functionality in Java (check out http://sourceforge.net/projects/ant-contrib first to see if someone already beat you to it).

If you're looking for more on Ant, the Ant manual is a great resource, but I'd also heartily recommend the book, Java Development with Ant, by Erik Hatcher and Steve Loughran, especially if you're working with Java as well as ColdFusion (and in the interest of full disclosure, I should mention Erik was my officemate for nearly a year while he wrote the book). I hate to admit it, but since I started using Ant, I find creating a build process for new applications (gulp!) fun. Okay, maybe not fun, but at least much less frustrating than DOS scripts, make, and the manual lists I used to use. In fact, right now I'm headed off to have a cup of coffee since I just kicked off my release build... "ant deploy". Phew! Tough day. Probably enough time for a venti today...

More Stories By John Ashenfelter

John Paul Ashenfelter is CTO and founder of TransitionPoint.com, a consulting firm based in central Virginia that specializes in developing and re-architecting ColdFusion Web applications for small- and mid-sized businesses. John Paul has been using ColdFusion since 1998 and is the author of three ColdFusion books as well as the upcoming Data Warehousing with MySQL.

Comments (2) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
Frengo 04/17/08 09:38:23 AM EDT

IMHO I have more much fun writing Ant Scripts than coding in Coldfusion, as with all other web scripting markup language :)

Gilbert 08/11/04 05:00:50 AM EDT

I have been trying to access the source code for the examples but I get an error message. Could you please post the example code again.

many thanks
Gilbert

@ThingsExpo Stories
I think DevOps is now a rambunctious teenager - it's starting to get a mind of its own, wanting to get its own things but it still needs some adult supervision," explained Thomas Hooker, VP of marketing at CollabNet, in this SYS-CON.tv interview at DevOps Summit at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
"MobiDev is a software development company and we do complex, custom software development for everybody from entrepreneurs to large enterprises," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Major trends and emerging technologies – from virtual reality and IoT, to Big Data and algorithms – are helping organizations innovate in the digital era. However, to create real business value, IT must think beyond the ‘what’ of digital transformation to the ‘how’ to harness emerging trends, innovation and disruption. Architecture is the key that underpins and ties all these efforts together. In the digital age, it’s important to invest in architecture, extend the enterprise footprint to the cl...
Data is the fuel that drives the machine learning algorithmic engines and ultimately provides the business value. In his session at Cloud Expo, Ed Featherston, a director and senior enterprise architect at Collaborative Consulting, discussed the key considerations around quality, volume, timeliness, and pedigree that must be dealt with in order to properly fuel that engine.
Two weeks ago (November 3-5), I attended the Cloud Expo Silicon Valley as a speaker, where I presented on the security and privacy due diligence requirements for cloud solutions. Cloud security is a topical issue for every CIO, CISO, and technology buyer. Decision-makers are always looking for insights on how to mitigate the security risks of implementing and using cloud solutions. Based on the presentation topics covered at the conference, as well as the general discussions heard between sessio...
IoT is rapidly becoming mainstream as more and more investments are made into the platforms and technology. As this movement continues to expand and gain momentum it creates a massive wall of noise that can be difficult to sift through. Unfortunately, this inevitably makes IoT less approachable for people to get started with and can hamper efforts to integrate this key technology into your own portfolio. There are so many connected products already in place today with many hundreds more on the h...
No hype cycles or predictions of zillions of things here. IoT is big. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, Associate Partner at M&S; Consulting, presented a step-by-step plan to develop your technology implementation strategy. He discussed the evaluation of communication standards and IoT messaging protocols, data analytics considerations, edge-to-cloud tec...
Announcing Poland #DigitalTransformation Pavilion
Digital Transformation is much more than a buzzword. The radical shift to digital mechanisms for almost every process is evident across all industries and verticals. This is often especially true in financial services, where the legacy environment is many times unable to keep up with the rapidly shifting demands of the consumer. The constant pressure to provide complete, omnichannel delivery of customer-facing solutions to meet both regulatory and customer demands is putting enormous pressure on...
DXWorldEXPO LLC announced today that All in Mobile, a mobile app development company from Poland, will exhibit at the 22nd International CloudEXPO | DXWorldEXPO. All In Mobile is a mobile app development company from Poland. Since 2014, they maintain passion for developing mobile applications for enterprises and startups worldwide.
CloudEXPO | DXWorldEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
The best way to leverage your CloudEXPO | DXWorldEXPO presence as a sponsor and exhibitor is to plan your news announcements around our events. The press covering CloudEXPO | DXWorldEXPO will have access to these releases and will amplify your news announcements. More than two dozen Cloud companies either set deals at our shows or have announced their mergers and acquisitions at CloudEXPO. Product announcements during our show provide your company with the most reach through our targeted audienc...
@DevOpsSummit at Cloud Expo, taking place November 12-13 in New York City, NY, is co-located with 22nd international CloudEXPO | first international DXWorldEXPO and will feature technical sessions from a rock star conference faculty and the leading industry players in the world.
Everything run by electricity will eventually be connected to the Internet. Get ahead of the Internet of Things revolution. In his session at @ThingsExpo, Akvelon expert and IoT industry leader Sergey Grebnov provided an educational dive into the world of managing your home, workplace and all the devices they contain with the power of machine-based AI and intelligent Bot services for a completely streamlined experience.
DXWorldEXPO | CloudEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
In his keynote at 19th Cloud Expo, Sheng Liang, co-founder and CEO of Rancher Labs, discussed the technological advances and new business opportunities created by the rapid adoption of containers. With the success of Amazon Web Services (AWS) and various open source technologies used to build private clouds, cloud computing has become an essential component of IT strategy. However, users continue to face challenges in implementing clouds, as older technologies evolve and newer ones like Docker c...
JETRO showcased Japan Digital Transformation Pavilion at SYS-CON's 21st International Cloud Expo® at the Santa Clara Convention Center in Santa Clara, CA. The Japan External Trade Organization (JETRO) is a non-profit organization that provides business support services to companies expanding to Japan. With the support of JETRO's dedicated staff, clients can incorporate their business; receive visa, immigration, and HR support; find dedicated office space; identify local government subsidies; get...
Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...