Alvaro Morata’s late goal sends La Roja to the final four for the Nations League as Spain defeats Portugal in Braga.
Spain needed to win to leapfrog Fernando Santos’ side atop Group A2 but had looked set to be frustrated, with Portugal enjoying the better of the first-half opportunities.
However, substitutions from Luis Enrique after the break changed the game, and Nico Williams’ header across goal was smashed in by Morata to steal a precious victory.
Both Diogo Jota and Cristiano Ronaldo of Manchester United missed chances to score as Portugal only needed a point to advance.
Spain will be joined in June’s finals by Croatia, Italy and the Netherlands, who are expected to host all the games.
Although Spain dominated the early possession, Portugal nearly opened the scoring with a fierce Ruben Neves drive that Unai Simon punched away.
They went close again after 33 minutes when Diogo Jota exquisitely jinked onto his right foot in the box before shooting at goal, but Simon was alert again to tip wide.
While Bruno Fernandes’ long-range effort into the side-netting then had Simon scrambling before half-time, the goalkeeper made another crucial intervention early in the second half to deny Cristiano Ronaldo from a tight angle.
Spain still had not registered a shot on target an hour in, so Luis Enrique sent on Barcelona pair Pedri and Gavi in the hopes of turning the game in his side’s favour, although it was fellow substitute Williams who made the telling contribution.
Morata had already gone close on a couple of occasions as Portugal keeper Diogo Costa was finally tested, and the Atletico Madrid striker netted the winner in dramatic fashion following Williams’ header.
Both teams are set to squeeze in one more friendly before the World Cup, with Portugal facing Nigeria on November 16 before Spain play Jordan the following day.