Reputation: 41268
I'd like to implement, in maven, a way of passing variables to POM via env variable but using a default value if not provided.
I created a minimalitic pom.xml
that prints FOO
and FOOBAR
vars. FOOBAR
has a default value:
<project>
<groupId>com.example</groupId>
<artifactId>test</artifactId>
<version>sprint-SNAPSHOT</version>
<modelVersion>4.0.0</modelVersion>
<properties>
<FOOBAR>1111111</FOOBAR>
</properties>
<build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-antrun-plugin</artifactId><version>1.1</version>
<executions><execution>
<phase>validate</phase><goals><goal>run</goal></goals>
<configuration><tasks>
<echo>FOO = ${FOO}</echo>
<echo>FOOBAR = ${FOOBAR}</echo>
</tasks></configuration>
</execution></executions>
</plugin></plugins></build>
</project>
Now, let’s try to run by passing a value from command line, or via env variable:
me@mymachine /d/mvn-tests
$ mvn install | grep FOO
[echo] FOO = ${FOO}
[echo] FOOBAR = 1111111
me@mymachine /d/mvn-tests
$ mvn install -DFOO=999 | grep FOO
[echo] FOO = 999
[echo] FOOBAR = 1111111
me@mymachine /d/mvn-tests
$ FOO=999 mvn install | grep FOO
[echo] FOO = 999
[echo] FOOBAR = 1111111
me@mymachine /d/mvn-tests
$ mvn install -DFOOBAR=555 | grep FOO
[echo] FOO = ${FOO}
[echo] FOOBAR = 555
me@mymachine /d/mvn-tests
$ FOOBAR=555 mvn install | grep FOO
[echo] FOO = ${FOO}
[echo] FOOBAR = 1111111
The last scenario is the one I don’t like: I’d prefer the env variable to take precedence over the property defined in the top of the XML (I want the one hardcoded in the XML to be the last-resort check).
So it seems that maven’s precedence is as follows:
Command line param > hardcoded XML value > env variable
I’d like to have:
Command line param > env variable > hardcoded XML value
Is there a way I can achieve the behaviour I want?
I’ve noticed I can use env.FOOBAR
to point unambiguously to the env variable:
...
<echo>FOO = ${FOO}</echo>
<echo>FOOBAR = ${FOOBAR}</echo>
<echo>env.FOOBAR = ${env.FOOBAR}</echo>
And then
me@mymachine /d/mvn-tests
$ FOOBAR=15 mvn install | grep FOO
[echo] FOO = ${FOO}
[echo] FOOBAR = 1111111
[echo] env.FOOBAR = 15
But how to say in pom.xml
sth that in a JS file would be ${env.FOOBAR || FOOBAR}
i.e. take one from env, if not specified, then take other one?
Upvotes: 1
Views: 340
Reputation: 32607
I think you'd be better off using Maven Profiles and defining the behavior/values based on that. Have a look at the documentation.
This way you'll be able to fine-tune the variables as you wish.
Upvotes: 2