Madrid had been looking for a replacement since Zinedine Zidane stepped down from the position last month, just days after winning a third consecutive Champions League trophy.
After guiding Spain easily through qualification to the World Cup finals, Lopetegui had agreed on a new contract up until Euro 2022 just last May and was not among the more than 20 names which had been linked with the Bernabeu vacancy in the local media over the past two weeks.
But with three days before Spain's World Cup opener against Portugal in Sochi, Madrid announced that the Basque tactician will leave that position after agreeing a three-year contract with the La Liga giants.
"Julen Lopetegui will be the Real Madrid coach after the celebration of the 2018 World Cup," the club's statement said. "Real Madrid C. F. announce that Julen Lopetegui will be the coach of the first team during the next three seasons."
Lopetegui has never lost a match as Spain coach since taking the reins in July 2016 in the wake of the European Championship, earning 14 wins with six draws for the second-longest unbeaten start by a coach in Spain's history.
As a player Lopetegui was a goalkeeper who spent spells as a backup at both Madrid and Barcelona, also playing for Rayo Vallecano and CD Logrones. He began his coaching career at Rayo in the second tier before moving to Madrid's Castilla youth side. He then coached Spain's under-19s, under-20s and under-21s
His only other top-flight club experience came in 18 up-and-down months at Porto, where he failed to win a trophy but reached the Champions League quarterfinals. He then succeeded mentor Vicente Del Bosque in the Spain job following La Roja's early exit at Euro 2016.
Lopetegui impressed in quickly blending together a new side which won nine of their 10 World Cup qualifiers and is among the favourites for this summer's finals in Russia. Spain will face Iran and Morocco in Group B after the challenge of Cristiano Ronaldo's Portugal in their opener on Friday.
The Spanish federation confirmed in a statement that Madrid will pay compensation to release Lopetegui from the remaining two years of his contract.
"The RFEF will receive the payment of the release clause so that the current national coach can sign for Real Madrid," the statement said. "The RFEF asks for the maximum respect to maintain normality in the national team camp ahead of our debut in the tournament against Portugal."
After the tournament, Spain will have to find a new boss ahead of the new UEFA Nations League, in which they will open against England and Croatia in September.