"Real Madrid announce that Julen Lopetegui will be the coach of the first team during the next three seasons," the Champions League winners said in a statement, adding that the 51-year-old "will join the club after Spain's participation in the World Cup".
Lopetegui will replace Zinedine Zidane as coach at the Santiago Bernabeu, after the Frenchman quit on May 31 in the wake of their Champions League final win over Liverpool in Kiev.
The news comes as a jolt for Spain, just three days before their opening game at the Russian World Cup against Iberian neighbours Portugal in Sochi.
Lopetegui and the Spain squad are currently at their training base in the southern Russian city of Krasnodar.
The Spanish Football Federation (RFEF) confirmed that Madrid will pay compensation to get Lopetegui out of the two years he has remaining on his contract with the national team.
He only signed an extension to his deal until 2020 last month.
"The RFEF will receive payment of the release clause so that the current national coach can join Real Madrid," read a statement, adding that Lopetegui would appear alongside federation president Luis Rubiales at a press conference at Spain's Russian training base on Wednesday at 11:30am (0830 GMT).
Spain are among the favourites to win the World Cup after an almost flawless qualifying campaign, and he will be hoping that the announcement does not overly unsettle his squad just before the competition gets under way.
Lopetegui's national squad includes six Real players in Dani Carvajal, Sergio Ramos, Nacho Fernandez, Marco Asensio, Isco and Lucas Vazquez.
"The RFEF requests the maximum respect in order to maintain normality in the national team camp ahead of our debut in the tournament against Portugal," added the federation's statement.