The 51-year-old, who has been in charge of the national team for the past two years, has agreed a three-year contract at the Bernabeu.
The move comes as a surprise, with Lopetegui not featuring prominently among the host of managers linked with the role since the departure of Zinedine Zidane days after Madrid’s 3-1 victory over Liverpool in the Champions League final.
The former goalkeeper made a sole league appearance for Madrid as a player and later turned out for rivals Barcelona.
Lopetegui previously coached Madrid’s feeder club Castilla in 2008/09 before taking charge of Spain’s youth teams.
He enjoyed success with the country’s youth sides, winning the U19 European Championship in 2012 before repeating the feat as U21 boss 12 months later.
Lopetegui’s forays into club management have been less successful, however. He was sacked from a brief spell in charge of Rayo Vallecano in Spain’s second division in 2003 and left Portuguese club Porto after failing to win any silverware from 2014-16.
Last month, he signed a contract extension to remain as Spain coach until 2020 but the call of Madrid has proved too strong to resist.
Zidane’s shock departure came after he had guided Madrid to a third straight Champions League title, but they finished a distant third as Barcelona took the honours in La Liga, and Lopetegui will be charged with closing what was a 17-point gap.
Among his first tasks will be resolving the future of Gareth Bale, with the Wales forward unhappy with his limited playing time under Zidane and in a powerful position after scoring twice off the bench in the Champions League final.