The reshuffling comes as Mr. Obama is making a critical decision about how many of the roughly 100,000 American troops in Afghanistan to withdraw starting this summer. The shift also places someone who has been immersed in government finances — Mr. Panetta was director of the White House budget office in 1993 and 1994 — at the forefront of what could be the most intense Pentagon budget battle in years.

Mr. Panetta, 72, was reluctant to leave the C.I.A., a senior administration official said. But after mulling it over for several weeks, he finally agreed to take the post in a conversation with the president on Monday evening.

The realignment is certain to raise questions about the militarization of intelligence and the extent to which the Pentagon and the C.I.A. are intertwined in Afghanistan, Iraq, Yemen and other trouble spots in the world.

Mr. Obama has been thinking about the changes since before Christmas, when he was handed a type-written list of candidates for the Pentagon post by his national security adviser, Thomas E. Donilon. Although Secretary of State Hillary Rodham Clinton was discussed in Washington as a candidate to succeed Mr. Gates, an administration official said “it was Leon the whole time.”