After you rescue Anora during the landsmeet talk to her and she'll suggest she should become queen, and you agree with her.
Then during the actual landsmeet you kill Loghain and you should then get to choose who becomes the ruler, choose Anora, she'll try to have Alistair executed and you can ask her to spare him as thanks for helping her become queen.
You also have to convince Alistair to perform the dark ritual with Morrigan otehrwise one of you will die fighting the archdemon.
That is the only way to get Alistair to stay in the Grey Wardens, all other methods have him become king, be executed, sacrifice himself or leave the wardens and becomne a drunk in Kirkwall.