The Spanish giants will pay City an initial fee of £15.5m for the 19-year-old, which could rise to £22m through a series of add-ons.
City have a 15% profit on any future sale, but that will rise to 40% should Madrid sell Diaz to Manchester United.
A Real Madrid statement said: “Real Madrid and Manchester City have agreed to the transfer of the player Brahim Diaz, who will be committed to the club for the remainder of the season and the next six, until June 30, 2025.
“After a medical examination to be held tomorrow, Monday January 7, the player will be presented at 1:30pm at the Santiago Bernabeu stadium.”
Diaz had rejected City’s offers of a new contract and was due to become a free agent in the summer.
“Today I close a chapter of my life and I say goodbye to Manchester City, the club where I have grown.
“I came here being a kid and now I am a professional footballer. Thank you to all the managers in the club, from the academy to the first team, for believing in me because they taught me not only to be a better player, but a better person,” Diaz said in a statement on Instagram.