The Wayback Machine - https://web.archive.org/web/20160322060745/http://python.sys-con.com/node/43787

Welcome!

Python Authors: Elizabeth White, AppDynamics Blog, XebiaLabs Blog, Hovhannes Avoyan, Carmen Gonzalez

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
SYS-CON Events announced today that LeaseWeb USA Inc., one of the world's largest hosting brands, will exhibit at SYS-CON's 18th International Cloud Expo®, which will take place on June 7-9, 2016, at the Javits Center in New York City, NY. LeaseWeb USA Inc. was established in 2011, a separate and distinct operating entity providing services in the USA. LeaseWeb is a trusted partner to mid-market companies, helping them find the right solution to their critical cloud-hosted needs from our global...
Symantec Corp. has announced the worldwide availability of Encryption Everywhere, a website security package available through web hosting providers. Encryption Everywhere lets web hosting providers integrate encryption into every website from the moment it is created. With the new web security service, hosting providers can offer a variety of flexible options, including basic website encryption included as part of any hosted service, and a number of premium security packages with increasingly s...
“Today’s generation of customers are always connected and well informed, but businesses are lagging behind in terms of both understanding and engaging their customers across all their channels in ways that are both relevant and consistent,” said Brian Walker, chief strategy officer, SAP Hybris. Only one in four companies are enabling omnichannel customer engagement, whereby they have a unified, “single view” of the customer and are delivering a consistent, contextual, and relevant experience a...
Zones, Inc., illustrated how technology solutions can improve patient care at the HIMSS16 Conference and Exhibition. Zones’ healthcare experts showcased technology to enhance patient care, ensure access to electronic medical and health records (EMR/EHR), design and implement mobility initiatives, and safeguard network and data security. Supporting every aspect of IT in the healthcare environment, Zones’ healthcare team can recommend the most productive and scalable IT solutions to ensure a high...
Electric Imp has expanded its focus to align with evolving commercial and industrial Internet of Things (IoT) opportunities. ”As our platform evolves, it is able to satisfy markets more demanding than the initial consumer segment,” said Hugo Fiennes, CEO and co-founder of Electric Imp. "Delivering over 500,000 units through our consumer device partners helped prove the scalability, reliability and usability of our platform, and now we are targeting our unique architecture at the problems facing...
@ThingsExpo has been named the ‘Top WebRTC Influencer' by iTrend. iTrend processes millions of conversations, tweets, interactions, news articles, press releases, blog posts - and extract meaning form them and analyzes mobile and desktop software platforms used to communicate, various metadata (such as geo location), and automation tools. In overall placement, @ThingsExpo ranked as the number one ‘WebRTC Influencer' followed by @DevOpsSummit at 55th.
SYS-CON Events announced today that Chetu Inc., a worldwide leader in custom software solutions for niche businesses, software-defined storage and data services platform, will exhibit at SYS-CON's @ThingsExpo, which will take place on June 7-9, 2016, at the Javits Center in New York City, NY. Founded in 2000, Chetu Inc. is a global provider of customized software development solutions and IT staff augmentation services for software technology providers. By providing clients with unparalleled ni...
Exosite has announced its Taipei Office has formally been established. Exosite’s Taiwan operations have grown from the Taichung team, primarily focused on research and development, into a full-service IoT enablement organization with development and consulting capabilities. The new Taipei office is located in the Taipei Minsheng Dunhua district, surrounded by all its hardware and channel partners. Exosite will devote its time to the Taiwan market and expand its business into the Asia-Pacific mar...
SYS-CON Events announced today BZ Media LLC has been named “Media Sponsor” of SYS-CON's 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. BZ Media LLC is a high-tech media company that produces technical conferences and expositions, and publishes a magazine, newsletters and websites in the software development, SharePoint, mobile development and Commercial Drone markets.
*This is part of a series of blogs examining Sensor-2-Server (S2S) communications, development, security and implementation. For the past two weeks, we’ve taken an in-depth look at what Sensor-2-Server communications are, how to implement these systems, and some of the specific aspects of communication that these systems facilitate. This week, for our final installment, we’ll examine some of the benefits, as well as security considerations, for S2S communications.
As devices, sensors, objects and people are given digital identities that connect them to the Internet by the billions, the need for security and privacy becomes a critical factor for both market adoption and safety. The 40-year-old security methods we now use on our PCs and networks cannot address many of these IoT devices.
Two-thirds of organizations implementing hybrid cloud report they’re already gaining competitive advantage from their hybrid environments and are nearly three times as likely to use it to assemble data assets or monetize data, according to findings released by IBM (NYSE: IBM). With a hybrid cloud approach, organizations can be selective about when to use cloud and when to use traditional IT infrastructure – delivering the best functionality while meeting speed and flexibility needs, as well a...
Internet of Things (IoT) platforms have evolved. Advances in technology make it possible for facilities to become more data-driven by connecting to energy assets, thereby improving building resiliency and reducing energy costs. By creating an Energy Network of Things, facilities can manage energy assets in real-time, institute system-wide operational oversight and compliance, execute energy efficiency programs, utilize real-time data, and support budgeting and asset planning across local and geo...
SYS-CON Events announced today CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 18th International Cloud Expo, which will take place on June 7–9, 2016, at the Javits Center in New York City, NY. CrowdReviews.com is the first buyer’s guide that ranks products and services based on client reviews.
For basic one-to-one voice or video calling solutions, WebRTC has proven to be a very powerful technology. Although WebRTC’s core functionality is to provide secure, real-time p2p media streaming, leveraging native platform features and server-side components brings up new communication capabilities for web and native mobile applications, allowing for advanced multi-user use cases such as video broadcasting, conferencing, and media recording.
SYS-CON Events announced today Object Management Group® has been named “Media Sponsor” of SYS-CON's 18th International Cloud Expo, which will take place on June 7–9, 2016, at the Javits Center in New York City, NY, and the 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that Pythian, a global IT services company specializing in helping companies adopt disruptive technologies to optimize revenue-generating systems, has been named "Bronze Sponsor" of SYS-CON's 18th Cloud Expo, which will take place on June 7-9, 2015 at the Javits Center in New York, New York. Pythian, a 400-person global IT services company that helps companies compete by adopting disruptive technologies, announced today that CEO Paul Vallée has been named “Diversi...
transform operational efficiency and safety for businesses and communities, especially during critical situations. During these critical events, man-made incidents or natural disasters, identifying and reaching employees with reliable and automated communications can not only protect business assets, but can be the difference between life and death. In his session at @ThingsExpo, Imad Mouline, chief technology officer for Everbridge, will highlight incident communications best practices and ...
Big Data, cloud, analytics, contextual information, wearable tech, sensors, mobility, and WebRTC: together, these advances have created a perfect storm of technologies that are disrupting and transforming classic communications models and ecosystems. In his session at @ThingsExpo, Erik Perotti, Senior Manager of New Ventures on Plantronics’ Innovation team, will provide an overview of this technological shift, including associated business and consumer communications impacts, and opportunities...
SYS-CON Events announced today that iDevices®, the preeminent brand in the connected home industry, will exhibit at SYS-CON's 18th International Cloud Expo® | @ThingsExpo, which will take place on June 7-9, 2016, at the Javits Center in New York City, NY. iDevices has announced that it has entered into a definitive agreement to sell the world’s #1 app-enabled grilling and cooking thermometer brands, namely iGrill® and Kitchen Thermometer, to Weber-Stephens Products, LLC. Weber®, the world’s lar...
Latest Stories
Cloud Expo & DevOps Summit 2015 West
KEYNOTES
Intellyx
Opening Keynote | Innovation in the Age of Digital Transformation
IBM
Day 2 Keynote | Geek Girls Are Chic: 5 Career Hacks
Octoblu
Day 3 Keynote | How We Built and Scaled an IoT Platform and Business
POWER PANELS
Cloud Expo Power Panel
Cloud Expo Power Panel | Cloud Computing: We Now Live in an API World
DevOps Summit Power Panel
DevOps Summit Power Panel | DevOps Five Years Later: What Does the Future Hold?
IoT Power Panel
@ThingsExpo Power Panel | The World's Many IoTs: Which Are the Most Important?
Cloud Expo & DevOps Summit 2015 East
KEYNOTES
IBM
Opening Keynote | Geek Girls Are Chic: 5 Career Hacks
Cisco
Day 2 Keynote | The Internet of Everything: Seizing the Opportunities
Virtustream
Day 3 Keynote at 16th Cloud Expo | Rodney Rogers, CEO of Virtustream
VENDOR PRESENTATIONS
Akana
General Session at 16th Cloud Expo | Laura Heritage, Director of API Strategy at Akana
CenturyLink
General Session at 16th Cloud Expo | David Shacochis, Vice President at CenturyLink
Cisco
General Session at 16th Cloud Expo | Paul Maravei, Regional Sales Manager, Hybrid Cloud, Cisco
CodeFutures
General Session at 16th Cloud Expo | Dan Lynn, CEO of CodeFutures Corporation
MetraTech, now part of Ericsson
General Session at 16th Cloud Expo | Esmeralda Swartz, VP, Marketing Enterprise & Cloud at Ericsson
SoftLayer
General Session at 16th Cloud Expo | Phil Jackson, Lead Technology Evangelist at SoftLayer
MetraTech, now part of Ericsson
General Session at 16th Cloud Expo | Esmeralda Swartz, VP, Marketing Enterprise & Cloud at Ericsson
Windstream
General Session at 16th Cloud Expo | Michael Piccininni, EMC, & Mike Dietze, Windstream
POWER PANELS
Cloud Expo Power Panel
Cloud Expo Power Panel | The Evolving Cloud: Where Are We Today?
DevOps Summit Power Panel
DevOps Summit Power Panel | Balancing the Three Pillars of DevOps
IoT Power Panel
@ThingsExpo Power Panel | The Internet of Things: A New Age
Microservices & IoT Power Panel
Microservices & IoT Power Panel at DevOps Summit
VIEW KEYNOTE WEBCASTS
Microsoft
Microsoft Opening Keynote | NoOps != No Operations
Qubell
DevOps Summit Keynote | Purpose-Defined Computing: The Next Frontier in Automation
PLATINUM SPONSORS
Verizon Enterprise
General Session | Verizon Pay-As-You-Go Model for Oracle Database Licenses Means Costs Savings and Business Benefits
Verizon Digital Media Services
Creating a Faster, More Secure Cloud
GOLD SPONSORS
Cisco
General Session | [Podcast] Hybrid Cloud – Different Clouds for Different Needs
SAP
General Session | Innovation with Cloud and Big Data Solutions That Will Revolutionize Your Business – Join SAP and Partners
SoftLayer
General Session | How to Architect and Optimize Your Cloud for Consistent Performance
Power Panels