In public, Mr. Trump said there were other “great companies” that should have a chance at the contract. But a speechwriter for former Defense Secretary Jim Mattis says in a book scheduled for publication next week that Mr. Trump had wanted to foil Amazon and give the contract to another company.

The issue quickly became radioactive at the Pentagon. The new defense secretary, Mark T. Esper, at first said he wanted to take several months to review the issue and then, a few days ago, recused himself from the bidding. He said he could not participate because his son worked for IBM, one of the competitors for the contract.

As recently as this month, the betting was that Microsoft would, at most, get only part of the contract and that the Pentagon would use multiple suppliers for its cloud services, as do many private companies. Microsoft was considered in the lead for other government cloud programs, including an intelligence contract; only recently has Microsoft opened enough classified server facilities to be able to handle data on the scale of the Pentagon contract.

“The acquisition process was conducted in accordance with applicable laws and regulations,” the Defense Department said in a statement on Friday. “All offerors were treated fairly and evaluated consistently with the solicitation’s stated evaluation criteria.”

Microsoft did not immediately have a comment. Amazon, which calls its cloud platform Amazon Web Services, or AWS, said in a statement that it was surprised by the decision.