Deus ex machina

Deus ex machina is the Latin version of an ancient Greek phrase "ἀπὸ μηχανῆς θεός". 
The phrase means "the god from the machine". It comes from the theatre of ancient Greece. They had a kind of crane for delivering gods onto the stage on wires.
By extension, the term means a plot device whereby a seemingly impossible problem is suddenly solved by means which do not follow normal logic.
For example, in Euripides' play "Alcestis", the heroine agrees to give up her own life in order to spare the life of her husband, Admetus. At the end Heracles shows up and seizes Alcestis from Death, restoring her to life and to Admetus. A more frequently cited example is Euripides' "Medea" in which the "deus ex machina" is used to take Medea (who has murdered people and babies) away from her husband Jason to the safety and civilization of Athens.
Aristotle criticized this device in his "Poetics." He argued that the resolution of a plot should follow the logic of the play. It should not come from something outside that logic.
There are many examples of the same dramatic device in modern movies and novels. For example, in H.G. Wells's "War of the Worlds", the aliens attacking Earth are suddenly killed by bacteria. The movie "Monty Python and the Holy Grail" makes fun of this plot device when the heroes barely escape from an animated monster because the animator died from a heart attack before finishing the movie's animation. Since the monster only existed in the animated scenes in the movie, the animator's death caused the monster to completely disappear from the movie.