BAGHDAD — Almost nine years after the first American tanks began massing on the Iraq border, the Pentagon declared an official end to its mission here, closing a troubled conflict that helped reshape American politics and left a bitter legacy of anti-American sentiment across the Muslim world.

As Defense Secretary Leon E. Panetta marked the occasion with a speech in a fortified concrete courtyard at the Baghdad airport, helicopters hovered above, underscoring the challenges facing a country where insurgents continue to attack American soldiers and where militants with Al Qaeda still regularly carry out devastating attacks against civilians.

“Let me be clear: Iraq will be tested in the days ahead — by terrorism, and by those who would seek to divide, by economic and social issues, by the demands of democracy itself,” Mr. Panetta said. “Challenges remain, but the U.S. will be there to stand by the Iraqi people as they navigate those challenges to build a stronger and more prosperous nation.”

Those words sounded an uncertain trumpet for a war that was begun in 2003 to rid Iraq of weapons of mass destruction that proved illusory. The conflict was also cast as an effort to bring democracy to the Middle East — another pretext that rang hollow during Iraq’s worst sectarian bloodletting, and that hampered Washington’s efforts in the past year to support the peaceful protesters of the Arab Spring.