title: Passing-through environment variables to Tomcat 7.0 web app context
body: <p>Apache Tomcat 7.0, CentOS 5.8 i386</p>
  
  <p>A web application needs a specific environment variable <strong>XY</strong> to be present in its context.
  This variable is set in <em>/etc/profile</em> as a result of a computation (i.e. not a static value) and it is also used by other native applications running on the same system (hence it has to be the environment variable approach).  </p>
  
  <p>Tomcat is started with a general script using a dedicated tomcat user and <em>sudo</em>.
  The first problem of passing <em>XY</em> through <em>sudo</em> is solved (thanks to stackoverflow) with the explicit definition within <em>/etc/sudoers</em>:  </p>
  
  <pre><code>Defaults    env_keep ="XY"
  </code></pre>
  
  <p>It means that the environment variable <em>XY</em> is preserved by <em>sudo</em> which is not the default case.</p>
  
  <p>Now the environment variable <em>XY</em> is visible in the tomcat process. This can be verified with <em>ps</em> and <em>/proc/tomcat-PID/environ</em> or an explicit <em>echo $XY</em> in */your_tomcat/bin/startup.sh* (which is called by the init.d script using <em>sudo</em>). But seeing <em>XY</em> in the tomcat process does not mean the web app can see it. The web app dumps its environment to the log file with help of </p>
  
  <pre><code>LOGGER.debug("Environment: " + System.getenv());  
  </code></pre>
  
  <p>the astonishing result for me was: no <em>XY</em> at all, although tomcat had it!</p>
  
  <p>After reading the context documentation of tomcat 7.0 (be careful to distinguish between 7.0 and older versions of tomcat) I added the following entry to */your_tomcat/conf/context.xml*:</p>
  
  <pre><code>&lt;Context&gt;
  ...
  &lt;Environment name="XY" value="INIT_VALUE" type="java.lang.String"/&gt;  
  ...
  &lt;/Context&gt;
  </code></pre>
  
  <p>Now the output of <em>System.getenv()</em> really contains my <em>XY</em> environment variable <strong>BUT</strong> it has the correct value from <em>/etc/profile</em> not the value <strong>INIT_VALUE</strong> I specified in <em>context.xml</em>. With other words my <em>/etc/profile</em> does overwrite the <strong>INIT_VALUE</strong>, which is what I needed but not what I expected as there is no word about this in the documentation.</p>
  
  <p>Did I find un-docmented behaviour that might be removed in later versions of tomcat or is this the way to go?
  So in the end I am happy having a working solution but I am not very confident that this is a recommended and proper way of passing-through environment variables.
  Any comments would be highly appreciated.</p>