BAGHDAD  Iraq’s leaders reached a tentative agreement late Wednesday night to create a unity government embracing the country’s major ethnic and religious factions, ending an eight-month political impasse and returning Nuri Kamal al-Maliki to power for a second term as prime minister.

The impasse had stoked fears of a return to sectarian violence. Yet the composition of the new government remained murky, and seemed to hold out the potential for more of the infighting, instability and vulnerability to insurgents that have hampered the country’s politics for years.

The agreement ensured, for now at least, the participation of Sunni Arabs, who supported the bloc led by Mr. Maliki’s chief rival, Ayad Allawi, which narrowly won the most seats in the March election. The deal was struck when Mr. Allawi’s group relented and agreed to join the new government, said Jaber al-Jaberi, one of Mr. Allawi’s chief allies, despite months of adamantly insisting it would never do so.

In exchange, Mr. Allawi’s bloc, called Iraqiya, was given the position of speaker of the Parliament as well as leadership of a newly created committee overseeing national security, officials from three factions said. The creation of the committee was a compromise pushed by the Obama administration to ensure the participation of Sunnis, Iraq’s former rulers, who have been underrepresented in the Iraqi government since the American invasion.