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 four and a half years in the job. The citation for the medal — the highest civilian honor the commander in chief can bestow — said that Gates had “selflessly dedicated his life to ensuring the security of the American people.”

The secretary appeared humbled by the honor, and genuinely surprised.

“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 secretary of defense under two, will retire to Washington state on Thursday. He will technically remain defense secretary until his successor, Leon Panetta, is sworn into office on Friday morning.

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 would 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 honor Gates in his final days, in part because he has been held in such high regard both at the Pentagon and 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 Gates’s service: “To say that we are grateful is to vastly understate our emotions on this day.”