Knowing that they needed to at least match Portugal's result to top the group, things looked bleak for 'La Roja' most of the night.
With just 14 minutes on the clock the 'Atlas Lions' took a shock lead, and Spain only had themselves to blame.
Experienced campaigners Andres Iniesta and Sergio Ramos suffered a breakdown in communication on halfway, allowing Khalid Boutaib to steal in race clear on goal.
Despite having covered some 40 yards, he kept his cool as he entered the box to slide an effort underneath David De Gea and open the scoring.
However, Spain looked unperturbed by that set-back and drew level just five minutes later.
Diego Costa, Andres Iniesta and the impressive Isco all combined to find the latter six yards out and he duly found the roof of the net to restore parity.
For all Spain's possession, either side could have led at the break, with Fernando Hierro's side continuing their defensive horror show by allowing Boutaib to race clear once again, only for De Gea to save his back four on that occasion.
On the stroke of the break Costa somehow failed to get enough contact on Iniesta's drilled cross from the left, despite having the goal to his mercy.
- Action-packed second half -
For all the action in the first period, the best was saved for later on as the second period caught everyone's imagination.
Nadiem Amrabat rattled the angle of post and bar for Herve Renard's side, before Romain Saiss had to be alert at the other end to head Isco's far-post header to safety from underneath his own crossbar.
A couple of Morocco forays forward aside, Spain always looked the most likely to score next, so imagine their surprise as Youssef En-Nesyri, a figure of ridicule at times during Málaga's unsuccessful battle against relegation this season, came of the bench to give the minnows the lead.
The 21-year-old outjumped everyone to meet a right-wing corner and power a header beyond a helpless David De Gea and into the top corner.
With Spain losing and Portugal winning, 'La Roja' looked set for a date with Uruguay in the last 16, only for yet more late drama to change their plans once again.
In Spain's hour of need, Hierro turned to Iago Aspas and the Celta forward repaid that faith by meeting Dani Carvajal's cross following a quickly-taken corner at the near post and back-heeling the ball beyond Munir in the first minute of stoppage time.
The goal was initially disallowed for offside, but a quick check with VAR overturned that call, which, coupled with a late leveller for Iran against Portugal meant that Spain ended the night top of Group B and thus handing them hosts Russia in the last 16.
June 25, 2018