The Master of Secrets finds himself caught in a web he can't escape in the most recent episode of Game of Thrones, and when Daenerys discovers that he has betrayed her, she's quick to make good on her promise to burn him alive. Given her current state of mind, the Dragon Queen's reaction makes sense, and Varys himself seems resigned to his fate. He's been watching his queen carefully for quite some time now, and before his death he's certain that she's not fit to rule the Seven Kingdoms. Varys betrays Daenerys because he's only ever had one motivation: to protect the realm.
Varys himself says he's served more rulers than anyone else in the Seven Kingdoms. He saw the madness of Daenerys's father firsthand, and he's there when Joffrey ascends to the throne for his short, but brutal reign. The Spider knows what to look for in terms of a leader, and he knows the danger signs as well. Sadly, the Mother of Dragons was exhibiting a number of signs that pointed toward danger — signs which ultimately lead to her going full Mad Queen on King's Landing after she puts Varys to death.
The way Varys sees it, his loyalty to a ruler is nothing compared to the loyalty he feels to the small folk, because he was once one of them. Yes, he uses his power to manipulate, but his machinations are in hopes of building a stable centre of power in order to provide the people of the realm with fair leadership. Before he begins penning letters revealing Jon's paternity, Varys observes the increasing sense of agitation that Daenerys is exhibiting as she waits for the right time to take the Iron Throne. He's also keenly aware of how displeased she is that she hasn't been met with love by the people of Westeros, and that her belief that she's destined for the throne likely means that she doesn't truly deserve to sit on it at all.
Because he witnessed the Mad King's reign, Varys is probably harder on Daenerys than he is on the other rulers he's served. As he reminds Tyrion, "Every time a Targaryen is born, the gods toss a coin in the air and the world holds its breath to see how it will land." Madness runs in her family, and after losing two of her dragons, as well as two of her closest allies in Missandei and Jorah, Daenerys is on the edge. It's hard for those who love her to see that, but because his allegiance isn't explicitly to the Dragon Queen, the Master of Secrets is in a much better position to realise that she's about to lose control.
Varys's inevitable betrayal comes about because he knows that Daenerys isn't the ruler he had hoped she would be, and as he always does, he sets about building a case for a more suitable person to ascend to power. Unfortunately for the Spider, this is one time that he couldn't out maneuver the ruler he hoped to usurp.