Goalkeeper Bono then saved Spain's second and third spot kicks from Carlos Soler and Sergio Busquets to allow Achraf Hakimi to put Morocco through by chipping his penalty down the middle.
Morocco had defended bravely against Spain that had over 75 percent of the ball, but failed to have a shot on target in open play, proving that although potency without control is nothing, control without potency also has its limits.
The game in the Education City Stadium was played in front of a packed house, with the vast majority supporting Morocco, and the fans erupted in jubilation when Hakimi (who came through the Real Madrid youth system) scored the winning penalty.
Spain coach Luis Enrique had a couple of surprises in his line-up, with Marcos Llorente, who hadn't played a minute in the World Cup, in at right back, while Marco Asensio returned in attack for top-scorer Alvaro Morata.
It was clear from the start of an intense first 45 minutes that Spain would not alter their passing game, despite losing to Japan in their last match.
Morocco were content to sit deep with their lines close together and close down spaces with Sofiane Boufal and Hakim Ziyech looking to break at pace.
The Moroccan fans made it feel like a home game for Morocco, who put in some full-blooded challenges, although Spain's 18-year-old Gavi - a teenage pitbull in midfield, showed he wasn't to be intimidated.
Loose play with his feet from Bono presented Spain with a chance, but Ferran Torres was offside when Jordi Alba lashed in a first time cross.
At the other end, Unai Simon was down to comfortably save Noussaur Mazraouri's long-range effort.
Morocco created two chances at the end of the first half, with Nayef Aguerd heading over after Boufal's cross from the left, before Jordi Alba did just enough to stop Ziyech heading back across goal with Simon back-peddling.
Chances were again at a premium at the start of the second half. Dani Olmo's drive from a narrow angle forced Bon to punch clear, before Spain coach Luis Enrique replaced Gavi and Asensio with Carlos Soler and Morata and Osasuna winger. Abde came on for Boufal for Morocco.
Spain still controlled the ball, and Nico Williams came on for Torres as Spain looked for forward momentum.
Williams' first action was a low cross but Olmo just failed to reach, and his second set up Morata to drag across goal from a narrow angle.
Suddenly Williams and Morata were finding some spaces, but it was Olmo, who nearly killed the match in 90 minutes with a curling free kick that Bono punched away at full stretch.
Williams and Morata carried Spain's threat in extra time, but the best chance fell to Morocco with Simon saving from Walid Cheddira with his feet. If Sarabia had his shooting boots on, he would have won it for Spain with the last kick of the game.
Morata had a chance too, but opted to pass rather than to shoot - and that showcased Spain's problems: control, but no potency.