Gavriel
Gavriel

Reputation: 19237

pom.xml environment variable with default fallback

I would like to be able to use an environment variable if it's set or a default fallback value that I set in pom.xml similar to ${VARIABLE:-default} in bash. Is it possible? Something like:

${env.BUILD_NUMBER:0}

Upvotes: 32

Views: 19279

Answers (2)

nerdwaller
nerdwaller

Reputation: 1863

I wasn't really satisfied with the accepted approach, so I simplified it a little.

Basically set a default property in the normal properties block, and only override when appropriate (instead of an effective switch statement):

<properties>
     <!-- Sane default -->
    <buildNumber>0</buildNumber>
    <!-- the other props you use -->
</properties>

<profiles>
    <profile>
        <id>ci</id>
        <activation>
            <property>
                <name>env.buildNumber</name>
            </property>
        </activation>
        <properties>
            <!-- Override only if necessary -->
            <buildNumber>${env.buildNumber}</buildNumber>
        </properties>
    </profile>
</profiles>

Upvotes: 52

StephaneM
StephaneM

Reputation: 4899

You could use profiles to achieve this:

<profiles> 
    <profile>
        <id>buildnumber-defined</id>
        <activation>
            <property>
                <name>env.BUILD_NUMBER</name>
            </property>
        </activation>
        <properties>
            <buildnumber>${env.BUILD_NUMBER}</buildnumber>
        </properties>
    </profile>
    <profile>
        <id>buildnumber-undefined</id>
        <activation>
            <property>
                <name>!env.BUILD_NUMBER</name>
            </property>
        </activation>
        <properties>
            <buildnumber>0</buildnumber>
        </properties>
    </profile>
</profiles>

A bit more verbose than bash...

Upvotes: 25

Related Questions