The president’s tweets announcing the departure of his defense secretary shocked officials at the Pentagon, who as recently as Thursday afternoon were insisting that Mr. Mattis had no intention of resigning.