Using Environment Variables
Problem
You want to obtain and use environment variables within Ant. This is a way to avoid hardcoding values in buildfiles.
Solution
Use a special form of the
<property>
task:[15]
<?xml version="1.0"?> <project name="envSample" default="deploy" basedir="."> <!-- Set up the 'env' prefix for environment variables --> <property environment="env"/> <!-- Abort the build if TOMCAT_HOME is not set --> <target name="checkTomcatHome" unless="env.TOMCAT_HOME"> <fail message="TOMCAT_HOME must be set!"/> </target> <target name="compile"> ... compile the code </target> <!-- Deploy the WAR file to TOMCAT_HOME/webapps --> <target name="deploy" depends="checkTomcatHome,compile"> <echo>Deploying to ${env.TOMCAT_HOME}</echo> <copy file="myapp.war" todir="${env.TOMCAT_HOME}/webapps"/> </target> </project>
Discussion
Although most operating systems support the concept of environment
variables, not all do. As a result, Sun deprecated
Java’s System.getEnv( ) method,
which used to return the values of environment variables. Undeterred
by this restriction, Ant’s programmers added the
ability to obtain environment variables using the technique shown
here.
Use the property task’s
environment
attribute to define a prefix,
conventionally “env”. Then use this
prefix when referencing environment variables in other parts of a
buildfile, as if you are referencing any normal Ant property. Our
example Ant buildfile uses the
TOMCAT_HOME
environment variable to deploy a Web Application ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access