It gave up three goals to Portugal in the opening game, a pulsating 3-3 tie in which Cristiano Ronaldo accounted for all the scoring for the Portuguese. Morocco has nowhere near the talent of Portugal, and has no one like Ronaldo. Yet it managed to expose defensive deficiencies on Monday that Hierro said he knows he’ll need to address if his team is to go any further.

“We can improve things,” Hierro said, adding, “Five goals in three matches isn’t the way forward.”

Morocco took advantage of Spain’s high defensive line and seized the lead after just 14 minutes following a mix-up between two of the most experienced players on Spain’s roster. When Andrés Iniesta — the veteran midfielder who scored the World Cup-winning goal in 2010 — and the captain Sergio Ramos got in each other’s way near the halfway line, Khalid Boutaib pinched the ball away from them and raced down the field for an easy finish.

Iniesta got some redemption, providing the assist for Isco five minutes later. But Morocco, backed by thousands of traveling supporters, refused to fade away in what was guaranteed to be its final match at this tournament. Boutaib made another run on goal following a simple throw down field a few minutes later. Spain’s goalkeeper, David de Gea, blocked Boutaib’s shot but could only watch as Noureddine Amrabat’s thunderbolt of a rebound bounced back off the woodwork early in the second half.

Then, with just nine minutes left in regulation time, the substitute Youssef En-Nesyri rose above the Spanish defense on a corner kick and headed home a goal to make it 2-1.

Spain looked to have blown the game, and their chance at winning the group, until Aspas got a flick on to Dani Carvajal’s cross in stoppage time. As he turned to celebrate, though, he could see the linesman’s flag raised, calling offside. The referee stepped in, making the signal for a video review, a new and unlikely emblem for the 2018 World Cup. Amid jeers and whistles, Spain had been saved.

As they trooped off the field, relieved to still be in the tournament, the Spanish players received another bit of good news. Iran’s V.A.R.-assisted penalty had saved Spain from the prospect of a meeting with Uruguay, the tiny South American nation that revels in its nickname of “aguafiestas”, or party poopers, for the number of times it has sent bigger nations crashing out of the World Cup. Instead, Spain faces Russia, which had been overrun by Uruguay earlier in the day.

“Luck of the champion? We will have to see what happens on July 1 at 5 p.m.,” Hierro said, looking forward to the next challenge in his unlikely World Cup coaching career.