diff --git a/changelog.html b/changelog.html
index b02f3a4ef9..8d69decc3f 100644
--- a/changelog.html
+++ b/changelog.html
@@ -72,6 +72,9 @@ Upcoming changes
Allow classworlds.conf to be externally configured for M3 builds
(issue 8905)
+
+ Configure the environment for Maven job type builds
+ (issue 8902)
diff --git a/maven-plugin/src/main/java/hudson/maven/MavenBuild.java b/maven-plugin/src/main/java/hudson/maven/MavenBuild.java
index 478b92e3ea..80d999ef8a 100644
--- a/maven-plugin/src/main/java/hudson/maven/MavenBuild.java
+++ b/maven-plugin/src/main/java/hudson/maven/MavenBuild.java
@@ -193,6 +193,18 @@ public class MavenBuild extends AbstractMavenBuild {
String opts = project.getParent().getMavenOpts();
if(opts!=null)
envs.put("MAVEN_OPTS", opts);
+ // We need to add M2_HOME and the mvn binary to the PATH so if Maven
+ // needs to run Maven it will pick the correct one.
+ // This can happen if maven calls ANT which itself calls Maven
+ // or if Maven calls itself e.g. maven-release-plugin
+ MavenInstallation mvn = project.getParent().getMaven();
+ if (mvn == null)
+ throw new AbortException(
+ "A Maven installation needs to be available for this project to be built.\n"
+ + "Either your server has no Maven installations defined, or the requested Maven version does not exist.");
+ mvn = mvn.forEnvironment(envs).forNode(Computer.currentComputer().getNode(), log);
+ envs.put("M2_HOME", mvn.getHome());
+ envs.put("PATH+MAVEN", mvn.getHome() + "/bin");
return envs;
}
diff --git a/maven-plugin/src/main/java/hudson/maven/MavenModuleSetBuild.java b/maven-plugin/src/main/java/hudson/maven/MavenModuleSetBuild.java
index 7ad0660de6..5a9615527e 100755
--- a/maven-plugin/src/main/java/hudson/maven/MavenModuleSetBuild.java
+++ b/maven-plugin/src/main/java/hudson/maven/MavenModuleSetBuild.java
@@ -147,6 +147,20 @@ public class MavenModuleSetBuild extends AbstractMavenBuild