According to the Washington Post, Petraeus was hoping to keep his job as CIA Director and thought the affair would not become public knowledge:
But some of his closest advisers who served with him during his last command in Iraq said Monday that Petraeus planned to stay in the job even after he acknowledged the affair to the FBI, hoping the episode would never become public. He resigned last week after being told to do so by Director of National Intelligence James R. Clapper Jr. on the day President Obama was reelected.
“Obviously, he knew about the relationship for months, he knew about the affair, he was in it, so yes, he was not going to resign,” said Peter Mansoor, a retired Army colonel and Petraeus’s executive officer during the Iraq “surge,” who spoke Monday with the former general for about half an hour. “But once he knew it was going to go public, he thought that resigning was the right thing to do. There is no way it would have remained private.”