Search code examples
antcontinuous-integrationphpunitjenkinsphing

Override environment variable when running on Jenkins


I'm testing a Zend Framework application using PHPUnit and Jenkins. I need to override the APPLICATION_ENV environment variable which is access using PHP's getenv in the PHPUnit bootstrap.php file:

<?php

// Define application environment
defined('APPLICATION_ENV')
|| define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'testing'));

... use APPLICATION_ENV to pick database, configuration, etc. ...

I have two environments: testing (for local machines) and testing-ci (for Jenkins machine). How can I set the variable to testing-ci when it runs in Jenkins? Is there any way to set it in build.xml for Ant or Phing?


Solution

  • Step 1: Add the environment variables to Jenkins.

    Open either the global or project-specific configuration page depending on your needs and scan down for the Environment variables section. Check the checkbox and use the Add button to add key/value pairs.

    These will be passed by Jenkins to your Ant build script.

    Step 2: Load them into Ant.

    Near the top of your Ant build.xml script, load all environment variables with an env prefix so they don't interfere with other properties.

    <property environment="env"/>
    

    Now all imported variables will be available using the env prefix, e.g. ${env.HOME}.

    Step 3: Pass them to PHPUnit.

    Assuming you're using the <exec> task to run PHPUnit, you can pass each needed variable to it using the <env> child element.

    <exec taskname="test" executable="phpunit">
        <env key="APPLICATION_ENV" value="${env.APPLICATION_ENV}"/>
        ...
    </exec>
    

    Note: You might want to try just the first step to see if Ant will pass the environment variables along to executed child processes, but I think the other two steps are good for making it clear what is required to other developers.