President Obama surprised Defense Secretary Robert M. Gates on Thursday with the Presidential Medal of Freedom, paying tribute to his four decades of public service at a regal farewell ceremony outside the Pentagon.

The honor came on Gates’s last day as defense secretary after 41 / 2 years in the job. The citation for the medal — the highest civilian honor the commander in chief can bestow — said that Gates has “selflessly dedicated his life to ensuring the security of the American people.”

The secretary appeared humbled and genuinely surprised by the honor.

“We should have known a couple of months ago that you were getting good at this covert ops stuff,” he told the president with a smirk.

Gates, who served in various roles under eight presidents and as defense secretary under two, was to retire to Washington state on Thursday. He will technically remain defense secretary until his successor, Leon Panetta, is sworn into office on Friday morning.

Panetta’s office at the CIA, in turn, will be filled by Gen. David H. Petraeus, whose nomination was confirmed by the Senate on Thursday in a unanimous vote. He is expected to assume the post in September. The CIA’s deputy director, Michael J. Morell, is expected to serve as interim director until then.

In a written farewell message distributed to troops this week, Gates said it had been the highest honor of his life to serve as defense secretary. Speaking to an audience that included Obama, Vice President Biden and others, he said Thursday that the commitment of U.S. forces will always stay with him.

“I’ll just say here that I will think of these young warriors — the ones that fought, the ones that keep on fighting, the ones that never make it back — until the end of my days,” he said.

The military has gone to unusual lengths to recognize Gates for his service, in part because he has been held in such high regard at the Pentagon and in most other quarters in Washington. In addition to the ceremony, he was honored at separate dinners hosted by Secretary of State Hillary Rodham Clinton and by Obama and the first lady. The Defense Department set up a special retrospective Web page listing his accomplishments.

“I believe the life of Bob Gates is a lesson,” Obama said, “especially to young Americans — a lesson that public service is an honorable calling, that we can pass our country better and stronger to those who follow.”

Adm. Mike Mullen, chairman of the Joint Chiefs of Staff, also paid tribute to Gates, saying of his service: “To say that we are grateful is to vastly understate our emotions on this day.”