The Russian club finalised the deal on Monday after the Frenchman successfully completed his medical.
Diarra was originally expected to join Anzhi on a one-year loan deal as Madrid signed Ghanaian midfielder Michael Essien from Chelsea on a season-long loan on transfer deadline day.
Anzhi also announced the signing of the 23-year-old forward Nikita Burmistov from Amkar Perm on Monday.
"The signings of these footballers totally correspond to the strategy of our club achieving top aims," CEO Ayvaz Kaziakhmedov said on Anzhi's official website.
"We are confident that, together with Lassana and Nikita, the club will fight for the most prestigious titles."
Diarra joined Madrid from Portsmouth in January 2009.